Skip to content

Commit

Permalink
[patch] add types
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Feb 1, 2024
1 parent 1efa8bf commit 49c4d4c
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 20 deletions.
20 changes: 20 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
root = true

[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 150

[CHANGELOG.md]
indent_style = space
indent_size = 2

[*.json]
max_line_length = off

[Makefile]
max_line_length = off
1 change: 1 addition & 0 deletions .github/workflows/node-aught.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ jobs:
range: '< 10'
type: minors
command: npm run tests-only
skip-ls-check: false

node:
name: 'node < 10'
Expand Down
16 changes: 16 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
type TypedArrayName =
| 'Int8Array'
| 'Uint8Array'
| 'Uint8ClampedArray'
| 'Int16Array'
| 'Uint16Array'
| 'Int32Array'
| 'Uint32Array'
| 'Float32Array'
| 'Float64Array'
| 'BigInt64Array'
| 'BigUint64Array';

declare function whichTypedArray(value: unknown): TypedArrayName | false | null;

export = whichTypedArray;
57 changes: 39 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,32 @@ var typedArrays = availableTypedArrays();
var $slice = callBound('String.prototype.slice');
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');

var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
var $indexOf = callBound('Array.prototype.indexOf', true) || /** @type {(array: readonly unknown[], value: unknown) => keyof array} */ function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};

/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array} TypedArray */
/** @typedef {'Int8Array' | 'Uint8Array' | 'Uint8ClampedArray' | 'Int16Array' | 'Uint16Array' | 'Int32Array' | 'Uint32Array' | 'Float32Array' | 'Float64Array' | 'BigInt64Array' | 'BigUint64Array'} TypedArrayName */
/** @type {{ [k in `\$${TypedArrayName}`]?: (receiver: TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call } & { __proto__: null }} */
var cache = { __proto__: null };
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
// @ts-expect-error TS won't narrow inside a closure
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
// @ts-expect-error TS won't narrow inside a closure
descriptor = gOPD(superProto, Symbol.toStringTag);
}
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(descriptor.get);
}
});
Expand All @@ -42,38 +49,52 @@ if (hasToStringTag && gOPD && getPrototypeOf) {
var arr = new g[typedArray]();
var fn = arr.slice || arr.set;
if (fn) {
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(fn);
}
});
}

/** @type {import('.')} */
var tryTypedArrays = function tryAllTypedArrays(value) {
var found = false;
forEach(cache, function (getter, typedArray) {
if (!found) {
try {
if ('$' + getter(value) === typedArray) {
found = $slice(typedArray, 1);
}
} catch (e) { /**/ }
/** @type {ReturnType<tryAllTypedArrays>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {Record<`\$${TypedArrayName}`, typeof cache>} */ /** @type {any} */ (cache),
/** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ function (getter, typedArray) {
if (!found) {
try {
// @ts-expect-error TODO: fix
if ('$' + getter(value) === typedArray) {
found = $slice(typedArray, 1);
}
} catch (e) { /**/ }
}
}
});
);
return found;
};

/** @type {import('.')} */
var trySlices = function tryAllSlices(value) {
var found = false;
forEach(cache, function (getter, name) {
if (!found) {
try {
getter(value);
found = $slice(name, 1);
} catch (e) { /**/ }
/** @type {ReturnType<tryAllSlices>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {any} */ (cache),
/** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ function (getter, name) {
if (!found) {
try {
// @ts-expect-error TODO: fix
getter(value);
found = $slice(name, 1);
} catch (e) { /**/ }
}
}
});
);
return found;
};

/** @type {import('.')} */
module.exports = function whichTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag) {
Expand Down
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"description": "Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.",
"license": "MIT",
"main": "index.js",
"types": "./index.d.ts",
"sideEffects": false,
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated",
Expand All @@ -30,6 +31,7 @@
"test:harmony": "nyc node --harmony --es-staging test",
"posttest": "aud --production",
"lint": "eslint --ext=js,mjs .",
"postlint": "tsc -p .",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
Expand Down Expand Up @@ -66,6 +68,14 @@
},
"devDependencies": {
"@ljharb/eslint-config": "^21.1.0",
"@types/call-bind": "^1.0.5",
"@types/for-each": "^0.3.3",
"@types/gopd": "^1.0.3",
"@types/is-callable": "^1.1.2",
"@types/make-arrow-function": "^1.2.2",
"@types/make-generator-function": "^2.0.3",
"@types/node": "^20.11.14",
"@types/tape": "^5.6.4",
"aud": "^2.0.4",
"auto-changelog": "^2.4.0",
"eslint": "=8.8.0",
Expand All @@ -76,7 +86,8 @@
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"safe-publish-latest": "^2.0.0",
"tape": "^5.7.4"
"tape": "^5.7.4",
"typescript": "^5.4.0-dev.20240131"
},
"testling": {
"files": "test/index.js",
Expand Down
10 changes: 9 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ var typedArrayNames = [

test('not arrays', function (t) {
t.test('non-number/string primitives', function (st) {
// @ts-expect-error
st.equal(false, whichTypedArray(), 'undefined is not typed array');
st.equal(false, whichTypedArray(null), 'null is not typed array');
st.equal(false, whichTypedArray(false), 'false is not typed array');
Expand Down Expand Up @@ -74,9 +75,13 @@ test('Arrow functions', { skip: arrows.length === 0 }, function (t) {

test('@@toStringTag', { skip: !hasToStringTag }, function (t) {
forEach(typedArrayNames, function (typedArray) {
// @ts-expect-error TODO: fix
if (typeof global[typedArray] === 'function') {
// @ts-expect-error TODO: fix
var fakeTypedArray = [];
// @ts-expect-error TODO: fix
fakeTypedArray[Symbol.toStringTag] = typedArray;
// @ts-expect-error TODO: fix
t.equal(false, whichTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array');
} else {
t.comment('# SKIP ' + typedArray + ' is not supported');
Expand All @@ -85,9 +90,12 @@ test('@@toStringTag', { skip: !hasToStringTag }, function (t) {
t.end();
});

/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor | BigInt64ArrayConstructor | BigUint64ArrayConstructor} TypedArrayConstructor */

test('Typed Arrays', function (t) {
forEach(typedArrayNames, function (typedArray) {
var TypedArray = global[typedArray];
// @ts-expect-error TODO: fix
/** @type {TypedArrayConstructor} */ var TypedArray = global[typedArray];
if (isCallable(TypedArray)) {
var arr = new TypedArray(10);
t.equal(whichTypedArray(arr), typedArray, 'new ' + typedArray + '(10) is typed array of type ' + typedArray);
Expand Down
49 changes: 49 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */

/* Projects */

/* Language and Environment */
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
"useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */

/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
"typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */
"resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */

/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
"checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
"maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
"declarationMap": true, /* Create sourcemaps for d.ts files. */
"noEmit": true, /* Disable emitting files from a compilation. */

/* Interop Constraints */
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */

/* Completeness */
//"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": [
"coverage"
]
}

0 comments on commit 49c4d4c

Please sign in to comment.