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

2

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

2 - npm Package Compare versions

Comparing version 1.0.2 to 2.0.0

56

array.js
'use strict'
/**
* Converts a map, iterable, object, or primitive into an array.
* @param {any} thingToConvert
* @param {object} options
* @param {bool} [options.detectIndexKeys=false] Whether or not map/object keys
* should be assumed to represent array indices if the keys go from 0...n-1
* @return {array}
*/
module.exports = function (thingToConvert, {detectIndexKeys = false} = {}) {
if (typeof thingToConvert === 'undefined' || thingToConvert === null || Number.isNaN(thingToConvert)) {
return []
}
const isInstanceOf = require('is-instance-of')
const isIterable = require('is-iterable')
const isNil = require('is-nil')
const isObject = require('is-object')
const sbo = require('sbo')
if (Array.isArray(thingToConvert)) {
return thingToConvert
}
module.exports = sbo(function toArray (x, {arrays = [], convertArrays, detectIndexKeys = false, maps = []} = {}) {
if (isNil(x) || Number.isNaN(x)) return []
if (Array.isArray(x) || (isInstanceOf(x, arrays) && !convertArrays)) return x
if (isInstanceOf(x, [Map, maps])) return Array.from(detectIndexKeys && keysLookLikeIndexes(x.keys()) ? x.values() : x)
if (isIterable(x) && typeof x !== 'string') return Array.from(x)
if (isObject(x)) return detectIndexKeys && keysLookLikeIndexes(Object.keys(x).sort()) ? Object.values(x) : Object.entries(x)
return [x]
})
if (thingToConvert instanceof Map) {
if (detectIndexKeys && JSON.stringify([...thingToConvert.keys()].map(String)) === JSON.stringify([...Array(thingToConvert.size).keys()].map(String))) {
return Array.from(thingToConvert.values())
} else {
return Array.from(thingToConvert)
}
function keysLookLikeIndexes (keys) {
let i = 0
for (const key of keys) {
if (key !== i && key !== String(i)) return false
i++
}
if (typeof thingToConvert[Symbol.iterator] !== 'undefined' && typeof thingToConvert !== 'string') {
return Array.from(thingToConvert)
}
if (typeof thingToConvert === 'object' && thingToConvert !== null) {
const objectKeysArray = [...Object.keys(thingToConvert)]
objectKeysArray.sort() // JS does not guarantee object key order, so sort the keys.
if (detectIndexKeys && JSON.stringify(objectKeysArray) === JSON.stringify([...Array(Object.keys(thingToConvert).length).keys()].map(String))) {
return objectKeysArray.map(key => thingToConvert[key])
} else {
return Object.entries(thingToConvert)
}
}
return [thingToConvert]
return i > 0
}
'use strict'
/**
* Converts an iterable, an object, or a primitive into an iterator.
* @param {any} thingToConvert
* @return {object}
*/
module.exports = function (thingToConvert) {
// Turn undefined/null/NaN into an empty iterator
if (typeof thingToConvert === 'undefined' || thingToConvert === null || Number.isNaN(thingToConvert)) {
return [][Symbol.iterator]()
}
const emptyIterator = require('empty-iterator')
const isIterable = require('is-iterable')
const isNil = require('is-nil')
const sbo = require('sbo')
// Turn a primitive into an iterator
if (typeof thingToConvert !== 'object') {
return [thingToConvert][Symbol.iterator]()
}
// Turn an Array, Set, Map, etc. into an iterator
if (Symbol.iterator in thingToConvert) {
return thingToConvert[Symbol.iterator]()
}
// Turn an object into an iterator
return Object.entries(thingToConvert)[Symbol.iterator]()
}
module.exports = sbo(function toIterator (x) {
if (isNil(x) || Number.isNaN(x)) return emptyIterator()
if (typeof x !== 'object') return [x][Symbol.iterator]()
if (isIterable(x)) return x[Symbol.iterator]() // Arrays, Sets, Maps, etc.
return Object.entries(x)[Symbol.iterator]() // Objects
})
MIT License
Copyright ©2017 John Lamansky
Copyright ©2017–2018 Fr. John Lamansky

@@ -5,0 +5,0 @@ Permission is hereby granted, free of charge, to any person obtaining a copy

'use strict'
/**
* Converts an array or object into a Map.
* @param {any} thingToConvert
* @param {object} options
* @param {Map|null} [options.fallback=new Map()]
* The Map to return if `thingToConvert` cannot be turned into a Map.
* Set to null to throw an error instead.
* @param {bool} [options.detectPairs=true]
* This option only applies if `thingToConvert` is an array.
* If set to `true`, an array of two-element arrays (the kind that’s used
* to construct a Map) will be treated as an array of key-value entries.
* @param {bool} [options.mirror=false]
* This option only applies if `thingToConvert` is an array.
* If set to `true`, array values are used as both keys and values
* (i.e. the keys and values mirror each other).
* If `false`, array indices (0 to n-1) are used as the Map keys.
* @return {Map}
*/
module.exports = function (thingToConvert, {fallback = new Map(), detectPairs = true, mirror = false} = {}) {
if (thingToConvert instanceof Map) {
return thingToConvert
}
const every = require('@lamansky/every')
const isArrayOfLength = require('is-array-of-length')
const isInstanceOf = require('is-instance-of')
const isIterable = require('is-iterable')
const isObject = require('is-object')
const map = require('map-iter')
const otherwise = require('otherwise')
const sbo = require('sbo')
if (Array.isArray(thingToConvert)) {
if (detectPairs && thingToConvert.every(item => Array.isArray(item) && item.length === 2)) {
return new Map(thingToConvert)
} else if (mirror) {
return new Map(thingToConvert.map(item => [item, item]))
} else {
return new Map(thingToConvert.map((item, index) => [index, item]))
}
module.exports = sbo(function toMap (x, {arrays = [], convertMaps = true, elseReturn = new Map(), elseThrow, detectPairs = true, maps = [], mirror = false} = {}) {
if (x instanceof Map) return x
if (isInstanceOf(x, maps)) return convertMaps ? new Map(x.entries()) : x
if (isIterable(x) && typeof x !== 'string') {
return new Map(
detectPairs && every(x, el => isArrayOfLength(el, 2)) ? x
: mirror ? map(x, el => [el, el])
: map(x, (el, i) => [i, el])
)
}
if (typeof thingToConvert === 'object' && thingToConvert !== null) {
return new Map(Object.keys(thingToConvert).map(
key => [key, thingToConvert[key]]
))
}
if (!(fallback instanceof Map)) {
throw new TypeError('Failed to convert input of an unrecognized type into a Map.')
}
return fallback
}
if (isObject(x)) return new Map(Object.entries(x))
return otherwise({elseReturn, elseThrow}, TypeError)
})
'use strict'
/**
* Converts a string or Number object into a primitive number.
* @param {any} thingToConvert
* @param {object} options
* @param {number|null} [options.fallback=0]
* The number to return if `thingToConvert` cannot be turned into a number.
* Set to `null` to throw an error instead.
* @param {bool} [options.finite=true]
* If true, only finite numbers are considered valid numbers.
* Therefore, if `thingToConvert` is `+Infinity` or `-Infinity`,
* the `fallback` will be returned.
* @param {bool} [options.round=false]
* If `true`, floats will be rounded to integers.
* @return {number}
*/
module.exports = function (thingToConvert, {fallback = 0, finite = true, round = false} = {}) {
let number = thingToConvert === null ? NaN : Number(thingToConvert)
if (Number.isFinite(number) || (!finite && !Number.isNaN(number))) {
if (round) number = Math.round(number)
return number
}
const otherwise = require('otherwise')
const qfn = require('qfn')
const sbo = require('sbo')
if (fallback instanceof Number) {
return Number(fallback)
} else if (typeof fallback !== 'number') {
throw new TypeError('Failed to convert input of an unrecognized type into a number.')
}
if (round) fallback = Math.round(fallback)
return fallback
}
module.exports = sbo(function toNumber (x, {elseReturn = 0, elseThrow, finite = true, round = false} = {}) {
const maybeRound = qfn(n => Math.round(n), round)
const number = x === null ? NaN : Number(x)
return maybeRound(Number.isFinite(number) || (!finite && !Number.isNaN(number)) ? number : otherwise({elseReturn, elseThrow}, TypeError))
})
'use strict'
const toString = require('./string')
const addCounter = require('add-counter')
const every = require('@lamansky/every')
const isArrayOfLength = require('is-array-of-length')
const isInstanceOf = require('is-instance-of')
const isIterable = require('is-iterable')
const isObject = require('is-object')
const map = require('map-iter')
const newObject = require('new-object')
const otherwise = require('otherwise')
const sbo = require('sbo')
/**
* Converts a Map or array into an object.
* @param {any} thingToConvert
* @param {object} options
* @param {object|null} [options.fallback={}]
* The object to return if `thingToConvert` cannot be turned into an object.
* Set to `null` to throw an error instead.
* @param {bool} [options.mirror=false]
* This option only applies if `thingToConvert` is an array.
* If set to `true`, array values are used as both keys and values
* (i.e. the keys and values mirror each other).
* If `false`, array indices (0 to n-1) are used as the object keys.
* If some array values have types which are among those supported as
* object keys (strings, numbers, and symbols), then mirroring will not happen.
* @return {object}
*/
module.exports = function (thingToConvert, {fallback = {}, mirror = false} = {}) {
if (thingToConvert instanceof Map) {
const object = {}
for (const [key, value] of thingToConvert.entries()) {
try {
object[typeof key === 'symbol' ? key : toString(key, {fallback: null})] = value
} catch (x) {
throw new TypeError('Cannot convert map to object because map has keys which objects do not support. Objects can only have string/number/symbol keys.')
}
}
return object
} else if (Array.isArray(thingToConvert)) {
if (thingToConvert.every(entry => Array.isArray(entry) && entry.length === 2)) {
const object = {}
for (const [key, value] of thingToConvert) {
object[key] = value
}
return object
} else if (mirror && thingToConvert.every(value => ['string', 'number', 'symbol'].includes(typeof value))) {
const object = {}
for (const value of thingToConvert) {
object[value] = value
}
return object
} else {
const object = {}
for (let i = 0; i < thingToConvert.length; i++) {
object[i] = thingToConvert[i]
}
return object
}
} else if (typeof thingToConvert === 'object' && thingToConvert !== null) {
return thingToConvert
module.exports = sbo(function toObject (x, {arrays = [], elseReturn = {}, elseThrow, maps = [], mirror = false} = {}) {
if (isInstanceOf(x, [Map, maps])) return newObject(x.entries(), {throwIfEquivKeys: true})
if (isIterable(x) && typeof x !== 'string') {
if (every(x, el => isArrayOfLength(el, 2))) return newObject(x)
if (mirror) return newObject(map(x, v => [v, v]), {throwIfEquivKeys: true})
return newObject(addCounter(x))
}
if (typeof fallback !== 'object' || fallback === null) {
throw new TypeError('Failed to convert input of an unrecognized type into an object.')
}
return fallback
}
if (isObject(x)) return x
return otherwise({elseReturn, elseThrow}, TypeError)
})
{
"name": "2",
"version": "1.0.2",
"version": "2.0.0",
"description": "The Type Conversion Library. Numbers, Strings, Arrays, Maps, Objects, and Iterators.",

@@ -20,3 +20,6 @@ "keywords": [

],
"author": "John Lamansky",
"author": {
"name": "Fr. John Lamansky",
"url": "lamansky.com"
},
"license": "MIT",

@@ -29,5 +32,20 @@ "homepage": "https://github.com/lamansky/2",

},
"dependencies": {
"@lamansky/every": "^1.0.0",
"add-counter": "^1.0.0",
"empty-iterator": "^1.0.0",
"is-array-of-length": "^1.0.0",
"is-instance-of": "^1.0.1",
"is-iterable": "^1.1.1",
"is-nil": "^1.0.1",
"is-object": "^1.0.1",
"map-iter": "^1.0.0",
"new-object": "^3.1.0",
"otherwise": "^1.1.0",
"qfn": "^1.0.1",
"sbo": "^1.1.0"
},
"devDependencies": {
"eslint-config-lamansky": "^1.0.0",
"mocha": "^3.2.0"
"mocha": "^5.2.0"
},

@@ -34,0 +52,0 @@ "scripts": {

@@ -8,12 +8,7 @@ # “2”: The Type Conversion Library

let data = {a: 1, b: 2}
data = toMap(data)
data = toArray(data)
data = toObject(data)
data = toIterator(data)
data = toArray(data)
data = toMap(data)
data = toObject(data) // {a: 1, b: 2}
const obj = {a: 1, b: 2}
obj::toMap()::toArray()::toObject()::toIterator()
::toArray()::toMap()::toObject() // {a: 1, b: 2}
data = '1.23'
let data = '1.23'
data = toNumber(data)

@@ -25,4 +20,6 @@ data = toString(data) // '1.23'

Requires [Node.js](https://nodejs.org/) 7.0.0 or above.
```bash
npm install 2 --save
npm i 2
```

@@ -118,7 +115,7 @@

// Can specify a fallback other than zero:
toNumber('not a number', {fallback: 100}) // 100
toNumber('not a number', {elseReturn: 100}) // 100
// You can choose to throw an error for invalid inputs by
// providing a null fallback:
toNumber('not a number', {fallback: null}) // throws error
// You can choose to throw an error for invalid inputs.
toNumber('not a number', {elseThrow: true}) // throws error
toNumber('not a number', {elseThrow: new TypeError('Not a number!')})

@@ -203,7 +200,6 @@ // Option to round floats:

toString(undefined) // ''
toString(undefined, {fallback: 'N/A'}) // 'N/A'
toString(undefined, {elseReturn: 'N/A'}) // 'N/A'
// You can choose to throw an error for invalid inputs by
// providing a null fallback:
toString(undefined, {fallback: null}) // throws error
// You can choose to throw an error for invalid inputs.
toString(undefined, {elseThrow: true}) // throws error

@@ -215,1 +211,13 @@ // String object => String

```
## Version Migration Guide
Here are backward-incompatible changes you need to know about.
### 1.x ⇒ 2.x
* `fallback` has been renamed to `elseReturn`
* Use `elseThrow: true` instead of `fallback: null`
* Unlike the old `fallback` parameter, `elseReturn` does _not_ type-enforce its values.
* `toObject` with `mirror: true` will now throw an error if any key would overwrite another key. In version 1, this would have been allowed.
* `toObject` with `mirror: true` will now allow an object to become an object key, so long as its string representation is not equivalent to that of any other key. In version 1, attempting to use an object as an object key would silently fail and would result in numeric index keys being used instead.
'use strict'
/**
* Converts a number or `toString`able object into a primitive string.
* @param {any} thingToConvert
* @param {object} options
* @param {string|null} [options.fallback='']
* The string to return if `thingToConvert` cannot be turned into a string.
* Set to `null` to throw an error instead.
* @return {string}
*/
module.exports = function (thingToConvert, {fallback = ''} = {}) {
if (typeof thingToConvert === 'string') {
return thingToConvert
}
const isObject = require('is-object')
const otherwise = require('otherwise')
const sbo = require('sbo')
if (thingToConvert instanceof String) {
return thingToConvert + ''
}
if (typeof thingToConvert === 'number' && Number.isFinite(thingToConvert)) {
return thingToConvert + ''
}
if (typeof thingToConvert === 'object' && thingToConvert !== null &&
thingToConvert.toString !== Object.prototype.toString) {
return String(thingToConvert)
}
if (fallback instanceof String) {
return fallback + ''
} else if (typeof fallback !== 'string') {
throw new TypeError('Failed to convert input of an unrecognized type into a string.')
}
return fallback
}
module.exports = sbo(function toString (x, {elseReturn = '', elseThrow} = {}) {
if (typeof x === 'string') return x
if (x instanceof String || Number.isFinite(x) || (isObject(x) && x.toString !== Object.prototype.toString)) return String(x)
return otherwise({elseReturn, elseThrow}, TypeError)
})

@@ -177,3 +177,3 @@ 'use strict'

it('should return the provided fallback if input is unconvertible', function () {
const map = toMap('not a map', {fallback: new Map([['a', 1], ['b', 2]])})
const map = toMap('not a map', {elseReturn: new Map([['a', 1], ['b', 2]])})
assert.strictEqual(map.get('a'), 1)

@@ -183,4 +183,4 @@ assert.strictEqual(map.get('b'), 2)

it('should throw error if input is unconvertible and fallback is not a Map', function () {
assert.throws(() => { toMap('not a map', {fallback: null}) }, TypeError)
it('should throw `elseThrow` if input is unconvertible', function () {
assert.throws(() => { toMap('not a map', {elseThrow: TypeError}) }, TypeError)
})

@@ -234,17 +234,13 @@ })

it('should return the provided fallback if number is invalid', function () {
assert.strictEqual(toNumber('not a number', {fallback: 2}), 2)
it('should return `elseReturn` if number is unconvertible', function () {
assert.strictEqual(toNumber('not a number', {elseReturn: 2}), 2)
})
it('should round fallback if `round` is true', function () {
assert.strictEqual(toNumber({}, {fallback: 3.3, round: true}), 3)
it('should round `elseReturn` if `round` is true', function () {
assert.strictEqual(toNumber({}, {elseReturn: 3.3, round: true}), 3)
})
it('should convert Number object fallback to primitive number', function () {
assert.strictEqual(typeof toNumber({}, {fallback: new Number(1)}), 'number') // eslint-disable-line no-new-wrappers
it('should throw `elseThrow` if input is unconvertible', function () {
assert.throws(() => { toNumber('not a number', {elseThrow: new RangeError()}) }, RangeError)
})
it('should throw error if number is invalid and fallback is not a number', function () {
assert.throws(() => { toNumber('not a number', {fallback: null}) }, TypeError)
})
})

@@ -276,7 +272,5 @@

it('should only `mirror` values to keys if all values can be object keys', function () {
const nonKeyable = {}
const object = toObject(['100', nonKeyable], {mirror: true})
assert.strictEqual(object[0], '100')
assert.strictEqual(object[1], nonKeyable)
it('should throw if mirrored values would be string-equivalent keys', function () {
toObject(['100', {}], {mirror: true})
assert.throws(() => { toObject(['100', {}, {}], {mirror: true}) })
})

@@ -294,10 +288,6 @@

it('should return the provided fallback if input is unconvertible', function () {
assert.strictEqual(JSON.stringify(toObject('not an object', {fallback: {a: 1}})), JSON.stringify({a: 1}))
it('should return `elseReturn` if input is unconvertible', function () {
assert.strictEqual(JSON.stringify(toObject('not an object', {elseReturn: {a: 1}})), JSON.stringify({a: 1}))
})
it('should throw error if input is unconvertible and fallback is not object', function () {
assert.throws(() => { toObject('not an object', {fallback: null}) }, TypeError)
})
it('should throw error if Map has keys that are not strings/numbers', function () {

@@ -379,13 +369,9 @@ assert.throws(() => { toObject(new Map([{}, 'test'])) }, TypeError)

it('should return the provided fallback if input is unconvertible', function () {
assert.strictEqual(toString({}, {fallback: 'test'}), 'test')
it('should return `elseReturn` if input is unconvertible', function () {
assert.strictEqual(toString({}, {elseReturn: 'test'}), 'test')
})
it('should convert String object fallback to primitive string', function () {
assert.strictEqual(typeof toString({}, {fallback: new String('test')}), 'string') // eslint-disable-line no-new-wrappers
it('should throw `elseThrow` if input is unconvertible', function () {
assert.throws(() => { toString({}, {elseThrow: true}) }, TypeError)
})
it('should throw error if input is unconvertible and fallback is not string', function () {
assert.throws(() => { toString({}, {fallback: null}) }, TypeError)
})
})

@@ -392,0 +378,0 @@

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