]> Lady’s Gitweb - Pisces/blob - function.js
0b9ebcc5510a4caaa767622b60427d5d536d4e2e
[Pisces] / function.js
1 // ♓🌟 Piscēs ∷ function.js
2 // ====================================================================
3 //
4 // Copyright © 2022 Lady [@ Lady’s Computer].
5 //
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
9
10 import { defineOwnProperty, isObject } from "./object.js";
11
12 /**
13 * Creates a bound function from the provided function using the
14 * provided this value and arguments list.
15 *
16 * ☡ As with call and construct, the arguments must be passed as an
17 * array.
18 */
19 export const bind = (() => {
20 const callBind = Function.prototype.call.bind(
21 Function.prototype.bind,
22 );
23 const bind = ($, boundThis, boundArgs) =>
24 callBind($, boundThis, ...boundArgs);
25 return bind;
26 })();
27
28 /**
29 * Calls the provided function with the provided this value and
30 * arguments list.
31 *
32 * ☡ This is an alias for Reflect.apply—the arguments must be passed
33 * as an array.
34 */
35 export const call = Reflect.apply;
36
37 /**
38 * Constructs the provided function with the provided arguments list
39 * and new target.
40 *
41 * ☡ This is an alias for Reflect.construct—the arguments must be
42 * passed as an array.
43 */
44 export const construct = Reflect.construct;
45
46 /** Returns whether the provided value is a constructor. */
47 export const isConstructor = ($) => {
48 if (!isObject($)) {
49 // The provided value is not an object.
50 return false;
51 } else {
52 // The provided value is an object.
53 try {
54 construct(
55 function () {},
56 [],
57 $,
58 ); // will throw if $ is not a constructor
59 return true;
60 } catch {
61 return false;
62 }
63 }
64 };
65
66 /**
67 * Returns a new function which calls the provided function with its
68 * first argument as the `this` value and the remaining arguments
69 * passed through.
70 *
71 * ※ This is effectively an alias for Function.prototype.call.bind.
72 */
73 export const makeCallable = (() => {
74 const functionCall = Function.prototype.call;
75 const callable = ($) => defineOwnProperty(
76 bind(functionCall, $, []),
77 "length",
78 { value: $.length + 1 },
79 );
80 return callable;
81 })();
82
83 /**
84 * Returns whether the provided object inherits from the prototype of
85 * the provided function.
86 */
87 export const ordinaryHasInstance = makeCallable(
88 Function.prototype[Symbol.hasInstance],
89 );
This page took 0.044065 seconds and 3 git commands to generate.