Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

bellajs

Package Overview
Dependencies
Maintainers
1
Versions
147
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bellajs

A useful helper for any javascript program

  • 6.4.51
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16K
increased by10.43%
Maintainers
1
Weekly downloads
 
Created
Source

BellaJS

Lightweight util for handling data type, string, data entries, datetime in your Node.js and browser apps.

NPM Build Status Coverage Status Dependency Status NSP Status

Contents

Setup

  • Node.js

    npm install bellajs --save
    
  • CDN

  • This library also supports ES6 Module, AMD and UMD style.

APIs

DataType detection

  • .isArray(Anything val): check if val is Array
  • .isBoolean(Anything val): check if val is Boolean
  • .isDate(Anything val): check if val is Date
  • .isElement(Anything val): check if val is likely a DOM element
  • .isEmail(Anything val): check if val is well-format email address
  • .isEmpty(Anything val): check if val is [], {} or ''
  • .isFunction(Anything val): check if val is Function
  • .isGeneratedKey(Anything val): check if val is a unique key generated by using bella.createId method
  • .isInteger(Anything val): check if val is an integer
  • .isLetter(Anything val): check if val is letter
  • .isNull(Anything val): check if val is null
  • .isNumber(Anything val): check if val is Number
  • .isObject(Anything val): check if val is Object
  • .isString(Anything val): check if val is String
  • .isUndefined(Anything val): check if val is Undefined

Immutable Array & Object

  • .stabilize(Array | Object val): return immutable version of val

This library provides a function named "stabilize" that you can pass through it an object or array to get back immutable version.

Here is an example in Node.js:

var stabilize = require('bellajs').stabilize;

let user = stabilize({
  name: 'Bob',
  age: 17
});

// user now is immutable
console.log(user);

// access the properties with get() or dot
let name = user.get('name'); // similar to user.name
console.log(name);

// you can change properties' value with set() method
// it will return a copy of user with new property

let guest = user.set('name', 'Tom');
console.log(guest.name); // => Tom

// the value of user.name can not be changed
console.log(user.name); // => Bob

// because it's immutable
user.name = 'Jerry';
console.log(user.name); // => Bob
Stabilize an object
stabilize(Object o);

Return an immutable object that has 2 methods "set()" and "get()".

Because the returned object is standard object, so you can still use the built-in methods in Object.prototype as normal.

.get(key)

Return value of specified property.

.set(key, value)

Return an new immutable object with new property.

Setter also accepts an object to allow to define many properties at the same time:

let car = stabilize({
  name: '',
  speed: 1000,
  color: 'black'
});

let tesla = car.set({
  name: 'Tesla',
  price: 40000
});

console.log(tesla);

tesla now is a new object with the following properties:

{
  name: 'Tesla',
  speed: 1000,
  color: 'black',
  price: 40000
}
Stabilize an array
stabilize(Array a);

Return an immutable array that has the following methods:

Because the returned array is standard array, so you can still use the built-in methods in Array.prototype as normal.

.unique()

Return a new array with no duplicate elements.

let a = stabilize([1, 2, 2, 3, 2, 4]);
let b = a.unique();

console.log(b); // => [ 1, 2, 3, 4 ]
.min()

Return the smallest value from an array of numbers.

let a = stabilize([1, 2, 2, 3, 8, 5, 2, 4]);
let b = a.min();

console.log(b); // => 1
.max()

Return the biggest value from an array of numbers.

let a = stabilize([1, 2, 2, 3, 8, 5, 2, 4]);
let b = a.max();

console.log(b); // => 1
.first()

Return the first element from array.

let a = stabilize([1, 2, 2, 3, 2, 4]);
let b = a.first();

console.log(b); // => 1
.last()

Return the last element from array.

let a = stabilize([1, 2, 2, 3, 2, 4]);
let b = a.last();

console.log(b); // => 4
.pick(count)

Extract count elements from array in randomly order.

let a = stabilize([1, 2, 2, 3, 2, 4]);
let b = a.pick(3);
console.log(b); // output an array of 3 random elements

Without count, this method returns a random element.

.insert(at, element1, element2, ...elementN)

Return a new array with new elements inserted at the position specified by first parameter.

let a = stabilize([1, 2, 3, 4]);
let b = a.insert(2, 'a');

console.log(b); // => [ 1, 2, 'a', 3, 4 ]
.append(element1, element2, ...elementN)

Return a new array with new elements added at the end.

let a = stabilize([1, 2, 3, 4]);
let b = a.append(5, 6, 7);

console.log(b); // => [ 1, 2, 3, 4, 5, 6, 7 ]
.remove(start, count)

Return a new array with count elements deleted beginning at start:

let a = stabilize([1, 2, 3, 4, 5, 6]);
let b = a.remove(3, 2); // remove 2 items from index 3, means 4 and 5

console.log(b); // => [ 1, 2, 3, 6 ]
.isort(compareFunction)

Return a new array sorted by compareFunction.

This method does the same thing as Array.sort, but immutable.

let users = stabilize([
  {
    name: "Bob",
    age: 28
  },
  {
    name: "Anne",
    age: 21
  },
  {
    name: "Jim",
    age: 33
  },
    {
    name: "Kate",
    age: 17
  }
]);
let sortedUsers = users.isort((a, b) => {
  let ag = a.age;
  let bg = b.age;
  if (ag === bg) {
    return 0;
  }
  return ag < bg ? -1 : 1;
});

console.log(sortedUsers);

Output:

[ { name: 'Kate', age: 17 },
  { name: 'Anne', age: 21 },
  { name: 'Bob', age: 28 },
  { name: 'Jim', age: 33 } ]
.msort([Number | String | Object opt])

Advanced version of .isort() that allows to sort an array by some flexible ways.

var points = stabilize([1, 5, 19, 6, 4, 11, 7, 22, 40, 3, 8]);
console.log('Array points, original:');
console.log(points);

console.log('Array points, lowest to highest:');
var a1 = points.msort(); // without parameter
console.log(a1);

console.log('Array points, descendant:');
var a2 = points.msort(-1);
console.log(a2);

var players = stabilize([
  {
    name: 'Jerome Nash',
    age: 24
  },
  {
    name: 'Jackson Valdez',
    age: 21
  },
  {
    name: 'Benjamin Cole',
    age: 23
  },
  {
    name: 'Manuel Delgado',
    age: 33
  },
  {
    name: 'Caleb McKinney',
    age: 28
  }
]);

console.log('\nList of players as it is:');
players.forEach((item) => {
  console.log([item.name, item.age].join(' | '));
});

console.log('\nSort by age from youngest to oldest:');
var players1 = players.msort('age');
players1.forEach((item) => {
  console.log([item.name, item.age].join(' | '));
});

console.log('\nSort by age from oldest to youngest:');
var players2 = players.msort({age: -1});
players2.forEach((item) => {
  console.log([item.name, item.age].join(' | '));
});

Results:

Array sorting easily

.ireverse()

This method does the same thing as Array.reverse, but immutable.

For example now you can reverse the above sortedUsers array:

let reversedUsers = sortedUsers.ireverse();
console.log(reversedUsers);

Output:

[ { name: 'Jim', age: 33 },
  { name: 'Bob', age: 28 },
  { name: 'Anne', age: 21 },
  { name: 'Kate', age: 17 } ]
.shuffle()

Return a clone of given array with shuffled elements.

let shuffledUsers = sortedUsers.shuffle();
console.log(shuffledUsers);

String manipulation

  • .createAlias(String s)
  • .encode(String s)
  • .decode(String s)
  • .ucfirst(String s)
  • .ucwords(String s)
  • .escapeHTML(String s)
  • .unescapeHTML(String s)
  • .stripTags(String s)
  • .stripAccent(String s)
  • .trim(String s [, Boolean nospace])
  • .truncate(String s, Number limit)
  • .repeat(String s, Number times)
  • .leftPad(String s, Number limit, String pad)
  • .rightPad(String s, Number limit, String pad)
  • .replaceAll(String s, String|Array search, String|Array replace)

Template

  • .template(String tpl)

Returns an object with .compile() method

Example:

var tpl = [
  '<article>',
    '<a href="{link}">{title}</a>',
    '<p>{content}</p>',
    '<p>',
      '<span>{author.name}</span>',
      '<span>{author.email}</span>',
    '</p>',
  '</article>'
].join('');

var data = {
  title: 'Hello world',
  link: 'http://google.com',
  content: 'This is an interesting thing, is that right?',
  author: {
    name: 'Dong Nguyen',
    email: 'ndaidong@gmail.com'
  }
}

var html = Bella.template(tpl).compile(data);
console.log(html);

DateTime

  • .now() return current date time
  • .time() return timestamp value at present
  • .date([Date | Number]) return an object with the following methods:
    • .format([String pattern])
    • .relativize()
    • .local()
    • .utc()

Example:

let d = bella.date(1479374694886);
d.local(); //=> Thu, 17 Nov 2016 16:24:54 GMT+0007
d.utc(); //=> Thu, 17 Nov 2016 09:24:54 GMT
d.relativize(); //=> 2 minutes ago
d.format('Y/m/d h:i:s'); //=> 2016/02/18 15:28:20

Default BellaJS DateTime pattern is 'D, M d, Y H:i:s A'.

Here are the available characters:

- Y: full year, ex: 2050
- y: short year, ex: 50
- F: full month name, ex: August
- M: short month name, ex: Aug
- m: month index with zero, ex: 08 (in 08/24/2050)
- n: short month name with no zero, ex: 8 (in 8/24/2050)
- S: the ordering subfix for date, ext: 1st, 2nd, 3rd, 4th
- j: day of the month, with no zero, ex: 3 (in 18/3/2050)
- d: day of the month, with zero, ex: 03 (in 18/03/2050)
- t: date in year
- w: weekday in number
- l: long name of weekday, ex: Sunday
- D: short name of weekday, ex: Sun
- G: hour, with no zero: 0 - 24
- g: hour, with no zero: 0 - 12
- h: hour, with zero:  00 - 24
- i: minute:  00 - 59
- s: second:  00 - 59
- a: am, pm
- A: AM, PM
- O: timezone

Other utils

.clone(Anything val):

Return a copy of val.

let b = [
  1, 5, 0, 'a', -10, '-10', '',
  {
    a: 1,
    b: 'Awesome'
  }
];

let cb = bella.clone(b);
console.log(cb);

cb now has the same values as b, while the properties are standalone, not reference. So that:

cb[7].a = 2;
cb[7].b = 'Noop';

console.log(b[7]);

What you get is still:

{
  a: 1,
  b: 'Awesome'
}
.copies(Object source, Object target[[, Boolean requireMatching], Array excepts]):

Copy the properties from source to target.

  • requireMatching: if true, BellaJS only copies the properties that are already exist in target.
  • excepts: array of the properties properties in source that you don't want to copy.

Example:

let a = {
  name: 'Toto',
  age: 30,
  level: 8,
  nationality: {
    name: 'America'
  }
};
let b = {
  level: 4,
  IQ: 140,
  epouse: {
    name: 'Alice',
    age: 27
  },
  nationality: {
    long: '18123.123123.12312',
    lat: '98984771.134231.1234'
  }
};

bella.copies(a, b);
console.log(b);

Output:

{
  level: 8,
  IQ: 140,
  epouse: {
    name: 'Alice',
    age: 27
  },
  nationality: {
    long: '18123.123123.12312',
    lat: '98984771.134231.1234',
    name: 'America'
  },
  name: 'Toto',
  age: 30
}
.createId([Number length [, String prefix]])
.equals(Anything a, Anything b)
.md5(String s)
.random([Number min [, Number max]]):

Test

git clone https://github.com/ndaidong/bellajs.git
cd bellajs
npm install
npm test

License

The MIT License (MIT)

Keywords

FAQs

Package last updated on 12 May 2017

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc