
Security News
RubyGems Adds Cooldown Feature to Bundler for Newly Published Gems
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.
Memory-efficient immutables in 13.5kB
libtuple is now ESM compliant!
You can install libtuple via npm:
$ npm install libtuple
(Groups, Records, and Dicts are just specialized Tuples)
Tuples are immutable. Any attempt to modify them will not throw an error, but will silently fail, leaving the original values unchanged.
const tuple = Tuple('a', 'b', 'c');
tuple[0] = 'NEW VALUE'; // This will not change the tuple, it will still be 'a'
console.log( tuple[0] ); // 'a'
Tuples can be members of other tuples. This works as expected:
console.log( Tuple(Tuple(1, 2), Tuple(3, 4)) === Tuple(Tuple(1, 2), Tuple(3, 4)) );
// true
Tuples and Groups can be looped over just like Arrays:
const tuple = Tuple(1, 2, 3);
for(const value of tuple) {
console.log(value)
}
Records, and Dicts can also be iterated just like normal objects:
const record = Record({a: 1, b: 2, c: 3});
for(const [key, value] of Object.entries(record)) {
console.log(key, value);
}
Tuples & Groups can be spread just like arrays:
const tuple = Tuple(1, 2, 3);
console.log([...tuple]); // [1, 2, 3]
Similarly, Records & Dicts can be spread into objects:
const record = Record({a: 1, b: 2, c: 3});
console.log({...record}); // {a: 1, b: 2, c: 3}
Simply import the functions from libtuple:
import { Tuple, Group, Record, Dict } from 'libtuple';
You can also import them via URL imports, or dynamic imports: (npm not required)
import { Tuple, Group, Record, Dict } from 'https://cdn.jsdelivr.net/npm/libtuple@0.0.7-alpha-4/index.mjs';
const { Tuple, Group, Record, Dict } = await import('https://cdn.jsdelivr.net/npm/libtuple/index.mjs');
Pass a list of values to the Tuple() function. This value will be strictly equivalent to any tuple generated with the same values:
const tuple123 = Tuple(1, 2, 3);
tuple123 === Tuple(1, 2, 3); // true
const tuple321 = Tuple(3, 2, 1);
tuple123 === tuple321; // false
This is true for tuples with objects as well:
const a = {};
const b = [];
const c = new Date;
console.log( Tuple(a, b, c, 1, 2, 3) === Tuple(a, b, c, 1, 2, 3) ); //true
A Group() is similar to a Tuple(), except they're not ordered:
Group(3, 2, 1) === Group(1, 2, 3); // true
A Record() works the same way, but works with keys & values, and is not ordered.
const [a, b, c] = [1, 2, 3];
Record({a, b, c}) === Record({c, b, a}); // true
A Dict() is like an ordered Record():
const [a, b, c] = [1, 2, 3];
Dict({a, b, c}) === Dict({a, b, c}); // true
Dict({a, b, c}) === Dict({c, b, a}); // false
A Schema allows you to define a complex structure for your immutables. It is defined by one or more SchemaMappers, which take a value and will either return it, or throw an error:
import { Schema as s } from 'libtuple';
const boolSchema = s.boolean();
boolSchema(true); // returns true
boolSchema(false); // returns false
boolSchema(123); // throws an error
You can create schemas for Tuples, Groups, Records, and Dicts:
import { Schema as s } from 'libtuple';
const pointSchema = s.tuple(
s.number(),
s.number(),
);
const pointTuple = pointSchema([5, 10]);
console.log(pointTuple);
const userSchema = s.record({
id: s.number(),
email: s.string(),
});
const userRecord = userSchema({id: 1, email: 'fake@example.com'});
console.log(userRecord);
Schema.parse() will return the parsed value, or NaN on error, since NaN is falsey, and NaN !== NaN.
import { Schema as s } from 'libtuple';
const boolSchema = s.boolean();
s.parse(boolSchema, true); // returns true
s.parse(boolSchema, false); // returns false
s.parse(boolSchema, 123); // returns NaN
Expand the sections below to see SchemaMapper documentation.
Drop the value (always maps to undefined)
The following methods will call s.number with additional constraints added:
The following methods will call s.string with additional constraints added:
// options.min & options.max are overridden for numeric comparison.
const positive = s.numericString({map: Number, min: Number.EPSILON});
const negative = s.numericString({map: Number, max: -Number.EPSILON});
negative('-100'); // -100
positive('100'); // 100
negative('5'); // ERROR
positive('-5'); // ERROR
// options.min & options.max are overridden for comparison with Date objects.
const after1994 = s.dateString({min: new Date('01/01/1995')});
after1994('07/04/1995'); // '01/01/1996'
after1994('07/04/1989'); // ERROR
const uuidSchema = s.uuidString();
uuidSchema('0ff5d941-f46a-4f4a-aec8-1d1ec117e2a3'); // '0ff5d941-f46a-4f4a-aec8-1d1ec117e2a3'
uuidSchema('0ff5d941'); // ERROR
const urlSchema = s.urlString();
urlSchema('https://example.com'); // 'https://example.com'
urlSchema('not a url'); // ERROR
const emailSchema = s.emailString();
emailSchema('person@example.com'); // 'https://example.com'
emailSchema('not an email'); // ERROR
const regexSchema = s.regexString();
regexSchema('.+?'); // 'https://example.com'
regexSchema('+++'); // ERROR
const base64Schema = s.base64String();
base64Schema('RXhhbXBsZSBzdHJpbmc='); // 'RXhhbXBsZSBzdHJpbmc=';
base64Schema('notbase64'); // ERROR;
const jsonSchema = s.jsonString();
jsonSchema('[0, 1, 2]'); // '[0, 1, 2]';
jsonSchema('not json'); // ERROR;
Map the value with the first matching SchemaMapper
import { Schema as s } from 'libtuple';
const dateSchema = s.or(
s.string({match: /\d\d \w+ \d\d\d\d \d\d:\d\d:\d\d \w+?/, map: s => new Date(s)}),
s.object({class: Date})
);
console.log( dateSchema('04 Apr 1995 00:12:00 GMT') );
console.log( dateSchema(new Date) );
Repeat a SchemaMapper r times
import { Schema as s } from 'libtuple';
const pointSchema = s.tuple(s.repeat(2, s.number()));
const point = pointSchema([5, 10]);
Match the value to a set of literals with strict-equals comparison.
import { Schema as s } from 'libtuple';
const schema = s.oneOf(['something', 1234]);
s.parse(schema, 1234); // 1234
s.parse(schema, 'something'); // 'something'
s.parse(schema, 'not on list'); // ERROR!
Map one or more values to a Tuple.
import { Schema as s } from 'libtuple';
const pointSchema = s.tuple(s.number(), s.number());
const point = pointSchema([5, 10]);
Map one or more values to a Group.
Map one or more properties to a Record.
import { Schema as s } from 'libtuple';
const companySchema = s.sRecord({
name: s.string(),
phone: s.string(),
address: s.string(),
});
const company = companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
});
console.log({company});
Map one or more values to a Dict.
import { Schema as s } from 'libtuple';
const companySchema = s.sDict({
name: s.string(),
phone: s.string(),
address: s.string(),
});
const company = companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
});
console.log({company});
Map n values to a Tuple. Will append each value in the input to the Tuple using the same mapper.
import { Schema as s } from 'libtuple';
const vectorSchema = s.nTuple(s.number());
const vec2 = vectorSchema([5, 10]);
const vec3 = vectorSchema([5, 10, 11]);
const vec4 = vectorSchema([5, 10, 11, 17]);
console.log({vec2, vec3, vec4});
Map n values to a Group. Will append each value in the input to the Group using the same mapper.
Map n properties to a Record. Will append additional properties without mapping or validation, if present.
import { Schema as s } from 'libtuple';
const companySchema = s.nRecord({
name: s.string(),
phone: s.string(),
address: s.string(),
});
const company = companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
openHours: '9AM-7PM',
slogan: 'We do business.',
});
Map n properties to a Dict. Will append additional properties without mapping or validation, if present.
Strictly map values to a Tuple. Will throw an error if the number of values does not match.
import { Schema as s } from 'libtuple';
const pointSchema = s.sTuple(s.number(), s.number());
const pointA = pointSchema([5, 10]);
const pointB = pointSchema([5, 10, 1]); // ERROR!
Strictly map values to a Group. Will throw an error if the number of values does not match.
Strictly map values to a Record. Will throw an error if the number of values does not match.
import { Schema as s } from 'libtuple';
const companySchema = s.nRecord({
name: s.string(),
phone: s.string(),
address: s.string(),
});
const company = companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
});
// ERROR!
companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
openHours: '9AM-7PM',
slogan: 'We do business.',
});
Strictly map values to a Dict. Will throw an error if the number of values does not match.
Exclusively map values to a Tuple. Will drop any keys not present in the schema.
import { Schema as s } from './index.mjs';
const pointSchema = s.xTuple(s.number(), s.number());
const pointA = pointSchema([5, 10]); // [5, 10]
const pointB = pointSchema([5, 10, 1]); // Also [5, 10]
console.log(pointB[0]); // 5
console.log(pointB[1]); // 10
console.log(pointB[2]); // undefined
Exclusively map values to a Group. Will drop any keys not present in the schema.
Exclusively map values to a Record. Will drop any keys not present in the schema.
const companySchema = s.xRecord({
name: s.string(),
phone: s.string(),
address: s.string(),
});
const company = companySchema({
name: 'Acme Corporation',
phone: '+1-000-555-1234',
address: '123 Fake St, Anytown, USA',
openHours: '9AM-7PM',
slogan: 'We do business.',
});
console.log({company});
Exclusively map values to a Dict. Will drop any keys not present in the schema.
In JavaScript, object comparisons are based on reference, not on the actual content of the objects. This means that even if two objects have the same properties and values, they are considered different if they do not reference the same memory location.
For example, the following comparison returns false because each {} creates a new, unique object:
Tuple( {} ) === Tuple( {} ); // FALSE!!!
Each {} is a different object in memory, so the tuples containing them are not strictly equal. This is an important behavior to understand when working with tuples that contain objects.
To get the same tuple, you need to use the exact same object reference:
const a = {};
Tuple( a ) === Tuple( a ); // true :)
A tuple is a type represented by a sequence of values. Unlike arrays, where [1, 2] !== [1, 2] (as they hold different object references), tuples provide a mechanism where Tuple(1, 2) === Tuple(1, 2). This ensures that tuples with the same values are always strictly equal, simplifying equality checks and enhancing memory efficiency.
For a sequence of primitives, this is trivial. Simply run JSON.stringify on the list of values and you've got a unique scalar that you can compare against others, and the object-reference problem is gone. Once you add objects to the mix, however, things can get complicated.
Stringifying objects won't work, since given almost any stringification mechanism, two completely disparate objects can be coerced to resolve the same value. That only leaves us with bean-counting. If we keep track of which objects and scalars we've seen, we can use the unique value of the object reference itself to construct a path through a tree of Maps where the leaves are the ultimate scalar value of the tuple. But in that case we'll use memory to hold objects and scalars in memory long after their tuples are useful. It seems we're backed into a corner here.
We could use trees of WeakMaps instead, however this case would only allow us to use objects, since scalars cannot be used as keys to a WeakMap. We'd end up with two disparate mechanisms, one for lists of only scalars, and one for lists of only objects. We just can't win here!
And that's where prefix-trees come in. Before constructing a tree of WeakMaps, the function will group all neighboring scalars into singular values. This will then leave us with a list of objects interspersed by singular scalars. Each scalar is then considered the prefix of the next object. When constructing or traversing the tree, first we come upon a node representing the object, then its prefix, then the next object in the chain. If the first (or any) object has no scalar prefix, we simply move directly to the next object. If the list ends in a scalar, simply add a terminator object reference as a key to the leaf, which holds the actual tuple object.
Organizing the hierarchy with the scalar prefixes after the objects allows us to exploit the WeakMap's garbage collection behavior. Once the object keys are GC'ed, so are the entries of the WeakMap. Holding a key here does not prevent objects from being GC'ed, so the branches of the internal tuple tree only stay in-memory as long as the objects they contain are in use.
Symbols cannot be used in Tuples. (i.e. created with Symbol.for(); more info) ⚠️ Node v19 & EarlierRun npm run test or node --test test.mjs in the terminal.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
FAQs
Memory-efficient tuple implementation.
The npm package libtuple receives a total of 24 weekly downloads. As such, libtuple popularity was classified as not popular.
We found that libtuple demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.

Security News
pnpm 11.5 now recognizes npm staged publish approvals in release metadata, preventing those releases from being mistaken for lower-trust package publishes.

Security News
Federal audit finds NIST lacked a plan to clear the NVD backlog, wasted funds on duplicate work, and delayed use of CISA data.