<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Celsius' Notes]]></title><description><![CDATA[Hire me as a freelancer for your mobile (iOS native, cross-platform with React Native), web and backend software needs.]]></description><link>https://celsiusnotes.com/</link><image><url>https://celsiusnotes.com/favicon.png</url><title>Celsius&apos; Notes</title><link>https://celsiusnotes.com/</link></image><generator>Ghost 5.80</generator><lastBuildDate>Fri, 17 Apr 2026 17:12:58 GMT</lastBuildDate><atom:link href="https://celsiusnotes.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[JavaScript: The Good Parts]]></title><description><![CDATA[<p>In this book Douglas Crockford distills and demonstrates the good parts of the JavaScript programming language and also tells us which parts of the language to steer clear of.</p><blockquote>We find the good parts in the products that we use. We value simplicity, and when simplicity isn&apos;t offered</blockquote>]]></description><link>https://celsiusnotes.com/javascript-the-good-parts/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e8</guid><category><![CDATA[javascript]]></category><category><![CDATA[book]]></category><category><![CDATA[programming]]></category><category><![CDATA[computer-science]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Mon, 04 Mar 2024 11:49:15 GMT</pubDate><content:encoded><![CDATA[<p>In this book Douglas Crockford distills and demonstrates the good parts of the JavaScript programming language and also tells us which parts of the language to steer clear of.</p><blockquote>We find the good parts in the products that we use. We value simplicity, and when simplicity isn&apos;t offered to us, we make it ourselves. My microwave oven has tons of features, but the only ones I use are cook and the clock. And setting the clock is a struggle. We cope with the complexity of feature-driven design by finding and sticking with the good parts.</blockquote><h2 id="my-notes-of-javascript-the-good-parts">My notes of JavaScript: The Good Parts</h2><p></p><blockquote>The value&#xA0;<code>NaN</code>&#xA0;is a number value that is the result of an operation that cannot produce a normal result.&#xA0;<code>NaN</code>&#xA0;is not equal to any value, including itself. You can detect&#xA0;<code>NaN</code>&#xA0;with the&#xA0;<code>isNaN(number)</code>&#xA0;function.</blockquote><blockquote>The&#xA0;<code>\u</code>&#xA0;convention allows for specifying character code points numerically.<br>&quot;A&quot; === &quot;\u0041&quot;</blockquote><blockquote>(<strong>Talking about the&#xA0;<code>for-in</code>&#xA0;statement</strong>)<br>It is usually necessary to test&#xA0;<code>object.hasOwnProperty(variable)</code>, to determine whether the propety name is truly a member of the object or was found instead on the prototype chain.</blockquote><blockquote>The values produced by&#xA0;<code>typeof</code>&#xA0;are &apos;number&apos;, &apos;string&apos;, &apos;boolean&apos;, &apos;undefined&apos;, &apos;function&apos;, and &apos;object&apos;. If the operand is an array or null, then the result is &apos;object&apos;, which is wrong.</blockquote><blockquote>JavaScript is a prototypal inheritance language. That means that objects can inherit properties directly from other objects. The language is class-free.</blockquote><blockquote>If a function is invoked with the&#xA0;<code>new</code>&#xA0;prefix, then a new object will be created with a hidden link to the value of the function&apos;s prototype member, and&#xA0;<code>this</code>&#xA0;will be bound to that new object.</blockquote><blockquote>When a function is not the property of an object, then it is invoked as a function:<br><code>var sum = add(3,4)</code><br>When a function is invoked with this pattern&#xA0;<code>this</code>is bound to the global object. This was a mistake in the design of the language. Had the language been designed correctly, when the inner function is invoked,&#xA0;<code>this</code>&#xA0;would still be bound to the&#xA0;<code>this</code>&#xA0;variable of the outer function.</blockquote><blockquote>Because of a design error&#xA0;<code>arguments</code>&#xA0;is not really an array. It is an array-like object.&#xA0;<code>arguments</code>&#xA0;has a length property, but it lacks all of the array methods.</blockquote><blockquote>Some languages offer the tail recursion optimization. This means that if a function returns the result of invoking itself recursively, then the invocation is replaced with a loop, which can significantly speed things up. Unfortunately, JavaScript does not currently provide tail recursion optimization. Functions that recurse very deeply can fail by exhausting the return stack.</blockquote><blockquote>Most languages with C syntax have block scope. All variables defined in a block ( a list of statements wrapped with curly braces) are not visible from outside of the block. The variables defined in a block can be released when execution of the block is finished. This is a good thing.<br>Unfortunately, JavaScript does not have block scope even though its block syntax suggests that it does. This confusion can be a source of errors.<br>(<strong>As of ES6, const and let variables are block-level scoped. var variables still are not.</strong>)</blockquote><blockquote>It is important to understand that the inner function has access to the actual variables of the outer functions and not copies in order to avoid the following problem:</blockquote><pre><code class="language-javascript">//BAD EXAMPLE
// When you click on a node, an alert box is supposed to display the ordinal of the node. But it always displays the number of nodes instead.
var add_the_handlers = function(nodes) {
    var i;
    for(i = 0; i &lt; nodes.length; i += 1) {
        nodes[i].onclick = function(e) {
            alert(i);
        };
    }
};

//BETTER EXAMPLE
//Make a function that assigns event handler functions to an array of nodes. When you click on a node, an alert box will display the ordinal of the node.
var add_the_handlers = function(nodes) {
    var helper = function(i) {
        return function(e) {
            alert(i)
        };
    };

    var i;
    for(i = 0; i &lt; nodes.length; i += 1) {
        nodes[i].onclick = helper(i);
    }
};
</code></pre><blockquote>The general pattern of a module is a function that defines private variables and functions; creates privileged functions which, through closure, will have access to the private variables and functions; and that returns the privileged functions or stores them in an accessible place.</blockquote><ul><li>Every function gets a&#xA0;<code>prototype</code>&#xA0;object because the language does not provide a way of determining which functions are intended to be used as constructors. The constructor property is not useful. It is the prototype object that is important.</li></ul><p>Constructing an object with the&#xA0;<code>new</code>&#xA0;keyword from a function is a 3 step process.</p><p>Example:</p><pre><code class="language-javascript"> function Mammal(name){
   this.name = name;
 }

  const mammal = new Mammal();
</code></pre><ol><li>Create a new empty object, setting its&#xA0;<strong>proto</strong>&#xA0;property to the .prototype property of the function invoked with the&#xA0;<code>new</code>&#xA0;keyword. (Functions have a .prototype property, objects do not)(An empty object is created which looks like {}. The&#xA0;<strong>proto</strong>&#xA0;property of the empty object is set to an empty object which has a&#xA0;<strong>proto</strong>&#xA0;and a constructor property, the value of which is the Mammal function )</li><li>Execute the code inside the constructor, setting the instance variables on the newly created object, if any, in the process.<br>(the only code inside the Mammal constructor sets the name instance)</li><li>Return the newly created object.</li></ol><ul><li>Inheriting in JS is setting the prototype property to an INSTANCE of the base class.</li></ul><blockquote>Object specification<br>It sometimes happens that a constructor is given a very large number of parameters.<br>This can be troublesome because it can be very difficult to remember the order of the arguments. In such cases, it can be much friendlier if we write the constructor to accept a single object specifier instead. That object contains the specification of the object to be constructed. So instead of:</blockquote><pre><code class="language-javascript">var myObject = maker(f, l, m, c, s);
//we can write

var myObject = maker({
    first: f,
    last: l,
    middle: m,
    state: s,
    city: c
});

</code></pre><blockquote>Instead, JavaScript provides an object that has some array-like characteristics. It converts array subscripts into strings that are used to make properties. It is significantly slower than a real array, but it can be more convenient to use. Retrieval and updating of properties work the same as with objects, except that there is a special trick with integer property names. Arrays have their own literal format. Arrays also have a much more useful set of built-in methods.</blockquote><ul><li>The length property is the largest integer property name in the array plus one. This is not necessarily the number of properties in the array:</li></ul><pre><code class="language-javascript">var myArray = [];
myArray.length   //0

myArray[1000000] = true;
myArray.length   //100001
//myArray contains one property.
</code></pre><p>(<strong>JS arrays are sparse arrays in most implementations</strong>)</p><blockquote>The [] postfix subscript operator converts its expression to a string using the expression&apos;s&#xA0;<code>toString</code>&#xA0;method if it has one. That string will be used as the property name. If the string looks like a positive integer that is greater than or equal to the array&apos;s current length and is less than 4,294,967,295, thenthe length of the array is set to the new subscript plus one.</blockquote><blockquote>Since JavaScript&apos;s arrays are really objects, the&#xA0;<code>for-in</code>&#xA0;statement can be used to iterate over all of the properties of an array. Unfortunately,&#xA0;<code>for-in</code>&#xA0;makes no guarantee about the order of the properties, and most array applications expect the elements to be produced in numerical order. Also, there is still the problem with unexptected properties being dredged up from the prototype chain.<br>(<strong>With ES6 you can use&#xA0;<code>for-of</code>&#xA0;to iterate arrays in numerical order</strong>)</blockquote><blockquote>Your comparison function should take two parameters and return 0 if the two parameters are equal, a negative number if the first parameter should come first, and a positive number if the second parameter should come first.<br>(<strong>The function basically answers the question: &apos;Should I swap these two params?&apos;</strong>)</blockquote><blockquote>The search method is like the&#xA0;<code>indexOf</code>&#xA0;method, except that it takes a regular expression object instead of a string. It returns the position of the first character of the first match, if there is one, or -1 if the search fails. The&#xA0;<code>g</code>&#xA0;flag is ignored. There is no&#xA0;<code>position</code>&#xA0;parameter.</blockquote><blockquote>Global Variables<br>The problem with JavaScript isn&apos;t just that it allows them, it requires them. JavaScript does not have a linker. All compilation units are loaded into a common global object.</blockquote><blockquote>In most languages, it is generally best to declare variables at the site of first use. That turns out the be a bad practice in JavaScript because it does not have block scope. It is better to declare all variables at the top of each function.</blockquote><blockquote>Implementations disagree on the type of regular expression objects. Some implementations report that:&#xA0;<code>typeof \a\</code>&#xA0;is &apos;object&apos;, and others say that it is &apos;function&apos;. It might have been more useful to report &apos;rexexp&apos;, but the standard does not allow that.</blockquote><blockquote>Binary floating-point numbers are inept at handling decimal fractions, so 0.1 + 0.2 is not equal to 0.3. This is the most frequently reported bug in JavaScript, and it is an intentional consequence of having adopted the IEEE Standard for Binary Floating-Point Arithmetic (IEEE 754). This standard is well-suited for many applications, but it violates most of the things you learned about numbers in middle school.<br>(<strong>Note, that this is not specific to JavaScript.</strong>)</blockquote><blockquote>JavaScript has a surprisingly large set of falsy values:</blockquote>
<!--kg-card-begin: html-->
<table style="box-sizing: border-box; border-collapse: collapse; margin-bottom: 1rem; width: 702.25px; border: 1px solid rgb(229, 229, 229); color: rgb(81, 81, 81); font-family: -apple-system, &quot;system-ui&quot;, &quot;Segoe UI&quot;, Roboto, &quot;Helvetica Neue&quot;, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Segoe UI Symbol&quot;, &quot;Noto Color Emoji&quot;; font-size: 18px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><thead style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><th style="box-sizing: border-box; text-align: inherit; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">Value</th><th style="box-sizing: border-box; text-align: inherit; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">Type</th></tr></thead><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">0</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">Number</td></tr><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">NaN (not a number)</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">Number</td></tr><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">&apos;&apos;(empty String)</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">String</td></tr><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">false</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">Boolean</td></tr><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">null</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229); background-color: rgb(249, 249, 249);">Object</td></tr><tr style="box-sizing: border-box;"><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">undefined</td><td style="box-sizing: border-box; padding: 0.25rem 0.5rem; border: 1px solid rgb(229, 229, 229);">Undefined</td></tr></tbody></table>
<!--kg-card-end: html-->
<blockquote><code>undefined</code>&#xA0;and&#xA0;<code>NaN</code>&#xA0;are not constants. They are global variables, and you can change their values. that should not be possible, and yet it is. Don&apos;t do this.<br>(<strong>Really, don&apos;t!</strong>)</blockquote><blockquote>The&#xA0;<code>eval</code>&#xA0;function also compromises the security of your application because it grants too much authority to the eval&apos;d text. And it compromises the performance of the language as a whole in the same way that the&#xA0;<code>with</code>&#xA0;statement does.</blockquote><blockquote>The&#xA0;<code>Function</code>&#xA0;constructor is another form of eval, and should similarly be avoided.</blockquote><blockquote>The browser provides&#xA0;<code>setTimeout</code>&#xA0;and&#xA0;<code>setInterval</code>&#xA0;functions that can take string arguments or function arguments. When given string arguments,&#xA0;<code>setTimeout</code>&#xA0;and&#xA0;<code>setInterval</code>&#xA0;act as&#xA0;<code>eval</code>. The string argument form also should be avoided.</blockquote><blockquote>In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too cryptic. So, as a matter of discipline, I don&apos;t use them anymore.</blockquote><blockquote>In many languages,&#xA0;<code>void</code>&#xA0;is a type that has no values. In JavaScript,&#xA0;<code>void</code>&#xA0;is an operator that takes an operand and returns&#xA0;<code>undefined</code>. this is not useful, and it is very confusing. Avoid&#xA0;<code>void</code>.</blockquote>]]></content:encoded></item><item><title><![CDATA[Custom URL Schemes in iOS]]></title><description><![CDATA[<p>URL schemes are essentially just specially formatted URLs linking to content within your app. You can use URL schemes in your iOS (and also macOS) apps to implement deep-linking and also to give third-party apps the ability to open your app.<br>You could, for instance, register a URL scheme and</p>]]></description><link>https://celsiusnotes.com/custom-url-schemes-in-ios/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e5</guid><category><![CDATA[programming]]></category><category><![CDATA[swift]]></category><category><![CDATA[ios]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 17 Jun 2020 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>URL schemes are essentially just specially formatted URLs linking to content within your app. You can use URL schemes in your iOS (and also macOS) apps to implement deep-linking and also to give third-party apps the ability to open your app.<br>You could, for instance, register a URL scheme and send out an email with a button or link to open your app.</p><p>However, apple strongly recommends using&#xA0;<a href="https://web.archive.org/web/20230629202122/https://developer.apple.com/ios/universal-links/">Universal Links</a>&#xA0;instead of URL schemes as they are more secure, albeit not as quick and easy to implement as URL schemes.</p><h2 id="limitations">Limitations</h2><p>You can&apos;t just register any URL scheme, as some are reserved for system apps. Following is a list of such URL schemes:&#xA0;<strong>http, https, tel, sms, facetime, facetime-audio, mailto</strong>. You can, however, launch the applications that support these URL schemes from within your app. More on that later.</p><h2 id="how-to-set-up-a-url-scheme-for-your-app">How to set up a URL Scheme for your app</h2><p>First, come up with the format for your app&apos;s URLs. We&apos;ll go with&#xA0;<code>celsiusapp://</code></p><p>Now, you should register your URL scheme. This will allow the system to redirect this URL scheme to your app. Do this by navigating to the Info tab in Xcode and scrolling down to &quot;URL Types&quot;. Click the &quot;+&quot; to add a new URL type.</p><p>Enter &quot;celsiusapp&quot; in the URL Schemes input field and &quot;com.celsiusnotes&quot; in the identifier field. The identifier serves to distinguish your app from others that have registered support for the same scheme. It is recommended to use a reverse DNS string of a domain that you own. Note, that this does not prevent other apps from registering the same scheme with the same identifier - even if they don&apos;t actually own that domain - and handling the URLs associated with that scheme and identifier.</p><p>Select &quot;Editor&quot; in the Role dropdown. Editor is for schemes that your app defines, while Viewer is for schemes that your app does not define but can handle.</p><figure class="kg-card kg-image-card"><img src="https://web.archive.org/web/20230629202122im_/https://celsiusnotes.com/content/images/2020/04/url_schemes-2.png" class="kg-image" alt="url_schemes-2" loading="lazy" width="1878" height="1204"></figure><p>Go ahead and build and run your app. Open Safari in your simulator or on your device and type in &quot;celsiusapp://&quot; in the address bar and hit enter. You should be prompted by Safari, asking whether you would like to open that page in the app you just built.</p><figure class="kg-card kg-image-card"><img src="https://web.archive.org/web/20230629202122im_/https://celsiusnotes.com/content/images/2020/05/screen-1.png" class="kg-image" alt="screen-1" loading="lazy" width="535" height="950"></figure><h2 id="handling-urls">Handling URLs</h2><p>As you might know, a URL consists of more parts than just the scheme. There is also the hostname, the path and the query (port number and fragment are not relevant here). When your app is opened through a URL scheme you have registered for it, it can handle the URL string upon being opened.</p><p>If your has&#xA0;<em>not</em>&#xA0;opted into Scenes, you will have to implement the&#xA0;<code>application(:open:options:)</code>&#xA0;method in the&#xA0;<code>AppDelegate.swift</code>&#xA0;file to handle incoming URLs. If, on the other hand, your app&#xA0;<a href="https://web.archive.org/web/20230629202122/https://celsiusnotes.com/ios-how-to-opt-out-of-using-scenes/"><em>has</em>&#xA0;opted into using Scenes</a>, as is the default for Xcode 11 and iOS 13, then you will have to implement the&#xA0;<code>scene(_:willConnectTo:options:)</code>&#xA0;and the&#xA0;<code>scene(_:openURLContexts:)</code>&#xA0;delegate methods in the&#xA0;<code>SceneDelegate.swift</code>&#xA0;class. The former delegate method is called when your app is launched, regardless of whether it was launched via a URL, while the latter will be called when your app is opened via a URL while running or after having been suspended in memory.</p><h3 id="while-opted-into-scenes">While opted into Scenes</h3><p>We&apos;re going to write a function to handle incoming URLs for both the&#xA0;<code>scene(_:willConnectTo:options:)</code>&#xA0;and the&#xA0;<code>scene(_:openURLContexts:)</code>&#xA0;delegate methods.</p><p>The&#xA0;<code>handleUrl()</code>&#xA0;function below accepts a URL as its only parameter and dissects that URL into its constituent parts: host, path and params. The function will prematurely return, should any of those parts not exist.<br>Then the function simply prints out the host, all path components and the keys (names) and values for all query parameters. In a real app, instead of simply printing out those parts, you would of course take some action, like navigating to a certain screen in your app based on the path and showing certain items based on the query parameters.</p><pre><code class="language-swift">    func handleURL(url: URL) {

        // A host, a path and query params are expected, else the URL will not be handled.
        guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
            let host = components.host,
            let _ = components.path,
            let params = components.queryItems else {
                NSLog(&quot;Invalid URL. Host, path and query params are expected&quot;)
                return
        }
        
        NSLog(&quot;host: \(host)&quot;)
        
        for (index, pathComponent) in url.pathComponents.enumerated() {
            NSLog(&quot;pathComponent \(index): \(pathComponent)&quot;)
        }
        
        for query in params {
            if let value = query.value {
                NSLog(&quot;Query param \(query.name): \(value)&quot;)
                continue
            }
            
            NSLog(&quot;Query param \(query.name) has no value&quot;)
        }
    }
</code></pre><p>To handle incoming URLs we simply call this function in both the&#xA0;<code>scene(_:willConnectTo:options:)</code>&#xA0;and the&#xA0;<code>scene(_:openURLContexts:)</code>&#xA0;delegate methods:</p><pre><code class="language-swift">    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
        
        
        // Since this function isn&apos;t exclusively called to handle URLs we&apos;re not going to prematurely return if no URL is present.
        if let url = connectionOptions.urlContexts.first?.url {
            handleURL(url: url)
        }
    }
</code></pre><pre><code class="language-swift">    // This delegate method is called when the app is asked to open one ore more URLs.
    // We&apos;re only going to handle one URL in this post. Handling, multiple URLs, however, is simply a matter of applying
    // the code to all other URLs in the `URLContexts` set.
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set&lt;UIOpenURLContext&gt;) {
        // Get the first URL out of the URLContexts set. If it does not exist, abort handling the passed URLs and exit this method.
        guard let url = URLContexts.first?.url else {
            return NSLog(&quot;No URL passed to open the app&quot;)
        }
        
        handleURL(url: url)
    }
</code></pre><p>Go ahead and build your app. Then, without closing your app, open the Safari app and type in&#xA0;<code>celsiusapp://hostpart/my/path/?name=celsius&amp;color=blue</code>&#xA0;into the address bar and hit go. After you now tap on open, you should see the following output in the Xcode console:</p><pre><code>host: hostpart
pathComponent 0: /
pathComponent 1: my
pathComponent 2: path
Query param name: celsius
Query param color: blue
</code></pre><p>Congrats, you have successfully handled an incoming URL!</p><p>This will also work when your app is launched after having been terminated. You just won&apos;t be able to see the output in the Xcode console, as your app disconnects from the Xcode debugger when it&apos;s closed. Open up the Console app by typing &quot;Console&quot; into the Spotlight search. Make sure your app is terminated. In the Console application, select your simulator or device and click on &quot;Clear&quot; to clear previous logs. Then open Safari in your simulator or on your device and type in&#xA0;<code>celsiusapp://hostpart/my/path/?name=celsius&amp;color=blue</code>&#xA0;again and hit go. If you now filter for &quot;PROCESS&quot; in the Console application and type in the name of your application, you should see the above host, path components etc. printed to the logs.</p><h3 id="while-opted-out-of-scenes">While opted out of Scenes</h3><p>If your app has not opted into scenes, as is the case for apps that support iOS versions &lt; 13, you need to handle the incoming URL in the&#xA0;<code>application(_:open:options:)</code>&#xA0;method in AppDelegate.swift</p><p>We can use the same&#xA0;<code>handleURL</code>&#xA0;function as we used above. So the only thing we need to do is implement the delegate function and pass the URL to the&#xA0;<code>handleURL</code>&#xA0;function.</p><pre><code class="language-swift">    func application(_ application: UIApplication,
                     open url: URL,
                     options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -&gt; Bool {
        
        self.handleURL(url: url)
        return true
    }   
</code></pre><p>That&apos;s all. You can get more information about the URL from the options object, which we are not going to do at this point, however.</p><p>You can try opening the app from a URL in Safari again as we did before. It should log the same output as it did above. Unlike when working with Scenes as shown above, we can handle URLs both when the app was launched from a terminated state and when it was opened from the background or a suspended state with the same method.</p><h2 id="launching-apps-with-url-scheme">LAUNCHING APPS WITH URL SCHEME</h2><p>You can also open an app via a URL programmatically. Use the&#xA0;<code>open(_:options:completionHandler:)</code>&#xA0;method of&#xA0;<code>UIApplication</code>&#xA0;to do that.<br>Use the completion handler to be notified when the URL has been delivered successfully.</p><pre><code class="language-swift">let url = URL(string: &quot;celsiusapp://hostpart/my/path/?name=celsius&amp;color=blue&quot;)
       
UIApplication.shared.open(url!) { (result) in
    if result {
       // The URL was delivered successfully!
    }
}
</code></pre><p>Note, if you want to try this out, you&apos;d have to do it from another app rather than the one we have been working with in this article.</p><h2 id="alternative-to-url-schemes">Alternative to URL Schemes</h2><p>I have already mentioned&#xA0;<a href="https://web.archive.org/web/20230629202122/https://developer.apple.com/ios/universal-links/">Universal Links</a>&#xA0;before in this article. Universal links are a more secure and sophisticated alternative to URL schemes. Apple recommends using Universal Links whenever possible.<br>If you do use URL schemes, make sure to validate URLs and limit the available actions incoming URL schemes may trigger. For instance, you should probably not allow incoming URLs to trigger destructive or mutating actions on the user&apos;s data.</p>]]></content:encoded></item><item><title><![CDATA[How to opt-out of using scenes in iOS 13 and above.]]></title><description><![CDATA[<p>When you start a new iOS project with the target version being &lt;= 13 you will automatically be opted-in to using scenes. While this is definitely the way to go in the future you might want to manually opt-out of using scenes.</p><h2 id="how-to-opt-out">How to opt-out</h2><p>First you have to remove</p>]]></description><link>https://celsiusnotes.com/how-to-opt-out-of-using-scenes-in-ios-13-and-above/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e4</guid><category><![CDATA[programming]]></category><category><![CDATA[swift]]></category><category><![CDATA[ios]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 17 Jun 2020 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>When you start a new iOS project with the target version being &lt;= 13 you will automatically be opted-in to using scenes. While this is definitely the way to go in the future you might want to manually opt-out of using scenes.</p><h2 id="how-to-opt-out">How to opt-out</h2><p>First you have to remove the &quot;Application Scene Manifast&quot; entry from Info.plist.</p><p>Next, remove the scene delegate class if there is one.</p><p>Then, remove all scene related delegate methods in your app delegate. Those methods will have the word scene in their names.</p><p>Also in your app delegate, add&#xA0;<code>var window: UIWindow?</code>&#xA0;if it&apos;s not already there.</p><p>That&apos;s it. If you&apos;ve correctly followed these steps, your app should now work without using scenes, reverting back to the old lifecycle.</p>]]></content:encoded></item><item><title><![CDATA[React Native: Android debug APK without development server]]></title><description><![CDATA[<p>By default React Native debug builds require the development server to run, as the server is responsible for providing the JS bundle and the assets in debug mode.<br>If however, you find yourself in need of a debug APK which can run without the development server, you can manually package</p>]]></description><link>https://celsiusnotes.com/react-native-android-debug-apk-without-development-server/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e3</guid><category><![CDATA[react-native]]></category><category><![CDATA[android]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Thu, 12 Sep 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>By default React Native debug builds require the development server to run, as the server is responsible for providing the JS bundle and the assets in debug mode.<br>If however, you find yourself in need of a debug APK which can run without the development server, you can manually package the debug bundle along with the generated APK.</p><p>There are two ways of accomplishing this:</p><h2 id="bundleindebug">bundleInDebug</h2><p>In your&#xA0;<strong>app/build.gradle</strong>&#xA0;file you should see a large commented out block that explains which settings you can set in the&#xA0;<code>project.ext.react</code>&#xA0;map inside your gradle file:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://celsiusnotes.com/content/images/2024/03/Screenshot-2024-03-07-at-15.48.55.png" class="kg-image" alt loading="lazy" width="805" height="795" srcset="https://celsiusnotes.com/content/images/size/w600/2024/03/Screenshot-2024-03-07-at-15.48.55.png 600w, https://celsiusnotes.com/content/images/2024/03/Screenshot-2024-03-07-at-15.48.55.png 805w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">Screenshot of app/build.gradle</span></figcaption></figure><p>The one that is interesting to us is&#xA0;<code>bundleInDebug: true</code>.<br>Look for the&#xA0;<code>project.ext.react</code>&#xA0;map (should be right after the commented out block) in your gradle configuration file and add the&#xA0;<code>bundleInDebug: true</code>&#xA0;entry to the map:</p><pre><code class="language-javascript">project.ext.react = [
    ...
    
    //ADD THIS LINE 
    bundleInDebug: true
    
    ...
]
</code></pre><p>This tells gradle to actually bundle the JS code and assets and package those files into the APK instead of serving them up from the dev server.</p><p>If you try this out, you will notice that while your app now runs without the dev server it will still display yellowbox warning messages. This is because it is still a development build. If you want to make it a production build, which will have no warnings and will have a minified JS bundle, add the&#xA0;<code>devDisabledInDebug: true</code>&#xA0;entry to the&#xA0;<code>project.ext.react</code>&#xA0;map.</p><pre><code class="language-javascript">project.ext.react = [
    ...
   
    bundleInDebug: true
    
    //ADD THIS LINE
    devDisabledInDebug: true
    
    ...
]
</code></pre><p></p><p><strong>Note:</strong>&#xA0;<em>debug</em>&#xA0;vs&#xA0;<em>release</em>&#xA0;refers to the Android build types, as specified in gradle, whereas&#xA0;<em>development</em>&#xA0;vs&#xA0;<em>production</em>&#xA0;affects the behaviour of the JS bundle.<br><br></p><p>When you now create an APK with&#xA0;<code>./gradlew assembleDebug</code>&#xA0;or by running&#xA0;<code>react-native run-android</code>&#xA0;it will be a debug APK, bundled with the minified JS bundle and all assets,capable of running without the dev server.</p><h2 id="react-native-bundle">react-native bundle</h2><p>If, for some reason, you want or need to manually invoke the&#xA0;<code>react-native bundle</code>&#xA0;command to bundle your JS and your assets, the way to build a development-server-independent APK is as follows:</p><p><code>react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/generated/assets/react/debug/index.android.bundle --assets-dest ./android/app/build/res/react/debug</code></p><p>Let&apos;s unpack what is happening there:</p><p>The&#xA0;<code>bundle</code>&#xA0;command is simply the command used to bundle the JS and the assets.</p><p><code>--dev false</code>&#xA0;tells it to not bundle it using development mode, i.e. disable warnings and minify the bundle. This corresponds to the&#xA0;<code>devDisabledInDebug: true</code>&#xA0;setting above.</p><p><code>--platform android</code>&#xA0;is self explanatory. Needs to be set, as the default is &quot;ios&quot;.</p><p><code>--entry-file index.js</code>&#xA0;is also quite self explanatory. If your entry file is named differently, then you should of course write that name there.</p><p><code>--bundle-output</code>&#xA0;here is where it gets interesting. How do we know the path for the bundle output? In order for gradle to be able to find the bundle it must be in a path where gradle expects it and also be named the way gradle expects it.<br>This information can be found in the&#xA0;<strong>node_modules/react-native/react.gradle</strong>&#xA0;file.</p><p>Find the line where the variables&#xA0;<code>jsBundleDir</code>&#xA0;and&#xA0;<code>resourcesDir</code>&#xA0;are being defined and assigned values to.</p><p><code>buildDir</code>&#xA0;is the&#xA0;<strong>android/app/build directory</strong>&#xA0;in your project and&#xA0;<code>targetPath</code>&#xA0;is either&#xA0;<em>debug</em>&#xA0;or&#xA0;<em>release</em>, depending on the build type of your build.</p><p>These are the paths where gradle expects to find the JS bundle and the assets to be packaged with the APK.</p><p>If, for some reason, you want to override those locations (or any other build settings), do not change them in the&#xA0;<strong>react.gradle</strong>&#xA0;file directly, but rather in your app level build.gradle file inside the project.ext.react map.</p>]]></content:encoded></item><item><title><![CDATA[Dynamic configurable text components with styled-components]]></title><description><![CDATA[<p>Up until recently when working with&#xA0;<a href="https://web.archive.org/web/20230208161500/https://www.styled-components.com/">styled-components</a>&#xA0;in my React Native apps I defined all my text components for every needed configuration in a single file like so:</p><pre><code class="language-javascript">import styled from &quot;styled-components&quot;;
import COLORS from &quot;../../global/colors&quot;;


/*
100    Extra Light or Ultra Light
200</code></pre>]]></description><link>https://celsiusnotes.com/dynamic-configurable-text-components-with-styled-components/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e2</guid><category><![CDATA[react-native]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 10 Apr 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Up until recently when working with&#xA0;<a href="https://web.archive.org/web/20230208161500/https://www.styled-components.com/">styled-components</a>&#xA0;in my React Native apps I defined all my text components for every needed configuration in a single file like so:</p><pre><code class="language-javascript">import styled from &quot;styled-components&quot;;
import COLORS from &quot;../../global/colors&quot;;


/*
100    Extra Light or Ultra Light
200    Light or Thin
300    Book or Demi
400    Normal or Regular
500    Medium
600    Semibold, Demibold
700    Bold
800    Black, Extra Bold or Heavy
900    Extra Black, Fat, Poster or Ultra Black
*/

export const Roboto10 = styled.Text`
        fontFamily: Roboto-Regular;
        fontSize: 10;
        fontWeight: normal;
        fontStyle: normal;
        lineHeight: 11;
        letterSpacing: 0;
        color: ${COLORS.purpleBrown};
`;

export const Roboto14 = styled.Text`
        fontFamily: Roboto-Regular;
        fontSize: 14;
        fontWeight: normal;
        fontStyle: normal;
        lineHeight: 24;
        letterSpacing: 0;
        color: ${COLORS.purpleBrown}
`;

export const Roboto16 = styled.Text`
        fontFamily: Roboto-Regular;
        fontSize: 16;
        fontWeight: normal;
        fontStyle: normal;
        lineHeight: 24;
        letterSpacing: 0;
        color: ${COLORS.purpleBrown}
`;

export const Roboto16Bold = styled.Text`
        fontFamily: Roboto-Regular;
        fontSize: 16;
        fontWeight: bold;
        fontStyle: normal;
        lineHeight: 24;
        letterSpacing: 0;
        color: ${COLORS.purpleBrown};
`;
</code></pre><p>This way of doing it is quite cumbersome because:</p><ul><li>you have to do a lot of writing.</li><li>you always have to check whether a component with a given configuration already exists or not (as to not add duplicates).</li><li>when you have to change the configuration, it might lead to unexpected UI changes in places you might not be aware of.</li></ul><p>So recently I a started writing dynamically configurable text components.</p><pre><code class="language-javascript">
/*
100    Extra Light or Ultra Light
200    Light or Thin
300    Book or Demi
400    Normal or Regular
500    Medium
600    Semibold, Demibold
700    Bold
800    Black, Extra Bold or Heavy
900    Extra Black, Fat, Poster or Ultra Black
*/

export type TextComponentConfig = {
    font: ?string,
    fontSize: ?number,
    lineHeight: ?number | ?string,
    fontWeight: ?number | string,
    fontStyle: ?number | string,
    color: ?string
}

const components = Object.create(null);

export default function TextComponents({
    font, fontSize, lineHeight, fontWeight, fontStyle,
}) {
    const key = `${font}_${fontSize}_${fontWeight}_${fontStyle}`;

    if (components[key]) {
        return components[key];
    }

    const TComp = styled.Text`
        fontFamily: ${font || &quot;&quot;};
        fontSize: ${fontSize || 16};
        fontWeight: ${fontWeight || &quot;normal&quot;};
        fontStyle: ${fontStyle || &quot;normal&quot;};
        lineHeight: ${lineHeight || fontSize || 16};
        letterSpacing: 0;
        color: ${COLORS.purpleBrown}
    `;
    components[key] = TComp;
    return TComp;
}
</code></pre><p>The&#xA0;<code>TextComponents</code>&#xA0;function takes an object that contains the configuration parameters for the desired text components. It then creates a key for that specific text component by simply stringing together all the passed parameter values into a&#xA0;<code>key</code>&#xA0;string. This&#xA0;<code>key</code>&#xA0;string is used to look up whether a component with that very same&#xA0;<code>key</code>&#xA0;has already been created and exists in the&#xA0;<code>components</code>&#xA0;object. If so, that component is returned. If not, we create a new component, save it in the&#xA0;<code>components</code>&#xA0;object and return it.</p><p>As you can see, I am not making use of all of the properties than can be used to style a Text component (for instance&#xA0;<code>lineHeight</code>, which should be trivial to add however.</p><h3 id="using-textcomponents">Using TextComponents</h3><p>The function can be used by passing the font configurations parameters as an object. Take a look at the following snippet to see how to dynamically generate and use a text component with the&#xA0;<code>TextComponents</code>&#xA0;function.</p><pre><code class="language-javascript">import React from &quot;react&quot;;
import TextComponents from &quot;./TextComponents&quot;;
const GreetingText = TextComponents({ font: &quot;Oswald-Regular&quot;, fontSize: 18, color: COLORS.lightBlack, fontWeight: &quot;bold&quot;, lineHeight: 25 });

export function HelloWorld(){
    return(
      &lt;GreetingText&gt;Hello World!&lt;/GreetingText&gt;
    );
}

</code></pre>]]></content:encoded></item><item><title><![CDATA[LC-3 VM in Swift]]></title><description><![CDATA[<p>I followed the&#xA0;<a href="https://web.archive.org/web/20230208180818/https://justinmeiners.github.io/lc3-vm/">Write your own Virtual Machine</a>&#xA0;tutorial to write a VM. I decided to write it in Swift, because I haven&apos;t written Swift in a while and miss writing Swift programs.</p><h2 id="code">Code</h2><p>The complete source code for the project can be viewed&#xA0;<a href="https://web.archive.org/web/20230208180818/https://github.com/Billydubb/LC3VM">here</a></p>]]></description><link>https://celsiusnotes.com/lc-3-vm-in-swift/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e1</guid><category><![CDATA[programming]]></category><category><![CDATA[swift]]></category><category><![CDATA[computer-science]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Fri, 22 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>I followed the&#xA0;<a href="https://web.archive.org/web/20230208180818/https://justinmeiners.github.io/lc3-vm/">Write your own Virtual Machine</a>&#xA0;tutorial to write a VM. I decided to write it in Swift, because I haven&apos;t written Swift in a while and miss writing Swift programs.</p><h2 id="code">Code</h2><p>The complete source code for the project can be viewed&#xA0;<a href="https://web.archive.org/web/20230208180818/https://github.com/Billydubb/LC3VM">here</a>.</p><p>I have only ever written one, also toy, VM before when I was working through the&#xA0;<a href="https://web.archive.org/web/20230208180818/https://www.nand2tetris.org/">Nand2Tetris</a>&#xA0;book and course some years back and had long forgotten some of the specifics, which is why this exercise was a good refresher.</p><p>You will notice that the code is in no way optimized, but it works, which is good enough for now.<br>Both memory and the registers are represented as UInt16 arrays. I could have gone with pointers to UInt16 values directly in memory, which probably would have been faster and more elegant.</p><p>Here are some interesting things I (re)learned while implementing this project.</p><h2 id="sign-extend">Sign Extend</h2><p>The LC-3 VM works with unsigned 16 bit integers. However, some of the instructions, such as the ST (store) instruction depicted below, call for arithmetic operations of an unsigned 16 bit integer with a another integer with fewer than 16 bits. The ST operation works by storing the contents specified by the register SR in the memory location specified by adding the program counter offset (PCOffset) bits 0 through 8 to the current value of the program counter (PC). The PC, much like all other registers in the LC8 machine is a 16 bit value, however, while the PCOffset is 9 bits wide.<br>To be able to go through with the addition of the two values, the PCOffset value will have to be sign extended. If the most significant bit of the PCOffset is 0, we simply fill up PCOffset with 0s to the left until it&apos;s 16 bits long. In case of a MSB of 1, PCOffset is filled up with 1s.<br>Sign extension of a value basically increases the number of bits of a binary number while preserving its sign (positive/negative).</p><h2 id="overflow-addition-in-swift">Overflow addition in Swift</h2><p>Unlike with the C programming language when adding two UInt16 integers in Swift (or any unsigned integers for that matter), there is no automatic overflow handling.<br>For instance the following code will give an EXC_BAD_INSTRUCTION error in Swift:</p><pre><code class="language-swift">let n: UInt16 = UInt16(UINT16_MAX)
print(n + 5) //EXC_BAD_INSTRUCTION
</code></pre><p>In order to opt in to overflow behavior for unsigned integers, you have to use the overflow addition (or subtraction or multiplication) operator&#xA0;<code>&amp;+</code>.</p><pre><code class="language-swift">let n: UInt16 = UInt16(UINT16_MAX)
print(n &amp;+ 5) //4
</code></pre><h2 id="terminal-modes">Terminal modes</h2><p>A terminal&apos;s default behavior for stdin is to buffer and pre-process keyboard inputs until a new line&#xA0;<code>\n</code>&#xA0;is encountered and only then pass it on to the running program. This mode is called cooked or canonical mode.<br>To implement the&#xA0;<code>checkKeyBoard()</code>&#xA0;function for the VM I needed every individual key press to be passed on to my program without any buffering and waiting for a new line character to be entered.<br>This requires the terminal to be set to raw or non-canonical mode.<br>We can set a terminal&apos;s attributes by reading them out with&#xA0;<code>tcgetattr()</code>&#xA0;into a struct, modifying that struct and then passing that modified struct into&#xA0;<code>tcsetattr()</code>.</p><h2 id="to-big-endian">To big endian</h2><p>Writing this VM served as a welcome refresher on endianness. It reminded me that endianness refers to the ordering of individual bytes of an integer word (while endianness can refer to individual bits, this is exceedingly rare in practice).<br>LC-3 VM programs are big endian. Most modern CPU architectures use little endian byte ordering. In order for the VM to work correctly on little endian machines, we had to swap the endianness of every read in 16 bit word from big to little endian representation.</p><h2 id="memory-mapped-registers">Memory mapped registers</h2><p>I was reminded of the existence of memory mapped registers while implementing this project. These registers are, as the name implies, not available in the register table, but instead have special addresses in memory. These registers can be read from and written to by simply treating them as regular memory addresses.<br>In the LC-3 machine, the keyboard status register (KBSR) and the keyboard data register (KBDR) are two such memory mapped registers. The KBSR indicates whether or not a keystroke on the keyboard has been registered. The KBDR holds the value (in our case ASCII code) of the key that has been pressed. The registers are polled in every iteration of the the VM while loop to check for keystrokes.</p><p>Writing this VM has been a lot of fun and very educational. If you have the time I would definitely recommend writing one yourself to deepen your understanding of some low level hardware concepts.</p>]]></content:encoded></item><item><title><![CDATA[How to use kill on Unix systems]]></title><description><![CDATA[<p><code>kill</code>&#xA0;is a Unix command that lets you send signals to processes, which is why the name &quot;kill&quot; is a bit misleading, as there are many signals that have nothing to do with terminating a process.</p><p>For security, a user can only send signals to processes which</p>]]></description><link>https://celsiusnotes.com/how-to-use-kill-on-unix-systems/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1e0</guid><category><![CDATA[unix]]></category><category><![CDATA[bash]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Thu, 07 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p><code>kill</code>&#xA0;is a Unix command that lets you send signals to processes, which is why the name &quot;kill&quot; is a bit misleading, as there are many signals that have nothing to do with terminating a process.</p><p>For security, a user can only send signals to processes which they own, unless they are the superuser.</p><p>You use the&#xA0;<code>kill</code>&#xA0;command by supplying it with a process id of the process you wish to send the signal to and optionally a signal, in the form of a number or a name. The default signal used when no signal is specified is SIGTERM.</p><h3 id="list-signals">List signals</h3><p><code>kill -l</code>&#xA0;lists all the signals on your OS. On my MacBook Pro with Mojave installed this is the output of running&#xA0;<code>kill -l</code>.</p><ol><li>SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL</li><li>SIGTRAP 6) SIGABRT 7) SIGEMT 8) SIGFPE</li><li>SIGKILL 10) SIGBUS 11) SIGSEGV 12) SIGSYS</li><li>SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGURG</li><li>SIGSTOP 18) SIGTSTP 19) SIGCONT 20) SIGCHLD</li><li>SIGTTIN 22) SIGTTOU 23) SIGIO 24) SIGXCPU</li><li>SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH</li><li>SIGINFO 30) SIGUSR1 31) SIGUSR2</li></ol><p>The mapping between numbers and signals can be different between Unix implementations.</p><h3 id="send-a-sigterm-signal-to-a-process">Send a SIGTERM signal to a process</h3><p><code>kill 64</code><br>will send a SIGTERM signal to the process with id 64. Notice how no signal number or name is specified. When that is the case, the default is to send the SIGTERM signal to the process.</p><h3 id="send-a-signal-by-number-or-name">Send a signal by number or name</h3><p>To send a signal by number, type:</p><p><code>kill -9 64</code>.<br>This will send the SIGKILL (see number to signal mapping above) signal to process with id 64. The SIGKILL signal will cause a process to terminate immediately. While for other signals it is possible for the processes to register signal handlers, for instance, to do some clean up before terminating, SIGKILL kills the specified process right away.<br>SIGSTOP is similar in as that can&apos;t be handled with a signal handler.</p><p>To send a signal by name, type:<br><code>kill -SIGQUIT 64</code>&#xA0;or&#xA0;<code>kill -s SIGQUIT 64</code><br>This will send the, you guessed it, SIGQUIT signal to the process with id 64.<br>The SIGQUIT signal terminates the process and dumps the core before it does so.</p><h3 id="terminal-signals">Terminal signals</h3><p>When you hit CTRL + C in your terminal, the signal sent to the current process is SIGINT. SIGINT asks the process to terminate.</p><p>For CTRL + Z it is SIGSTP. SIGSTP is the terminal equivalent to SIGSTOP. It suspends the process which can then be resumed at a later time with SIGCONT.</p>]]></content:encoded></item><item><title><![CDATA[How to destructure a JavaScript object without a declaration.]]></title><description><![CDATA[<p>This is how you destructure a JS object:</p><pre><code class="language-javascript">const book = {
    author: &quot;Bobby B.&quot;,
    title: &quot;Ladida&quot;
}
const {author, title} = book;
console.log(author) // Bobby B.
console.log(title) // Ladida
</code></pre><h3 id="how-not-to-do-it">How not to do it</h3><p>However, sometimes you might need to destructure an object without declaring the identifiers</p>]]></description><link>https://celsiusnotes.com/how-to-destructure-a-javascript-object-without-a-declaration/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1df</guid><category><![CDATA[programming]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Mon, 04 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>This is how you destructure a JS object:</p><pre><code class="language-javascript">const book = {
    author: &quot;Bobby B.&quot;,
    title: &quot;Ladida&quot;
}
const {author, title} = book;
console.log(author) // Bobby B.
console.log(title) // Ladida
</code></pre><h3 id="how-not-to-do-it">How not to do it</h3><p>However, sometimes you might need to destructure an object without declaring the identifiers on the left hand side as new variables, for instance, when those variables exist in the same scope and you can&apos;t redeclare the variables.</p><p>You might try to do something like this, which will give you a SyntaxError, as author and title have already been declared in the same scope:</p><pre><code class="language-javascript">let author;
let title;

const book = {
    author: &quot;Bobby B.&quot;,
    title: &quot;Ladida&quot;
};

const {author, title} = book;
</code></pre><p>Since that didn&apos;t work, you might try something like in the following snippet. If you do, you will be met with a: &quot;SyntaxError: Unexpected token =&quot;. This is because opening braces&#xA0;<code>{</code>&#xA0;at the beginning of a statement are interpreted as a block in JavaScript. And blocks cannot be assigned to.</p><pre><code class="language-javascript">let author;
let title;

const book = {
    author: &quot;Bobby B.&quot;,
    title: &quot;Ladida&quot;
};

{author, title} = book;
</code></pre><h3 id="shadowing-inside-loops">Shadowing inside loops</h3><p>Another example is when you loop through an array of items want to break the loop as soon as you encounter an item that holds a certain value.</p><p>Consider the following snippet. We have an array of books, consisting of an author and a title. We want to loop through it and assign the author and the title to the&#xA0;<code>author</code>&#xA0;and&#xA0;<code>title</code>&#xA0;variables that are declared before the loop, so that we can access those variables after the loop.</p><pre><code class="language-javascript">const books = [{}, {}, {}, {} ,{}, {author: &quot;Bobby. B&quot;, title: &quot;Ladida&quot;}, {}, {}, {}, {} ,{}];

let author;
let title;

for(let book of books ){
    // destructure author and title out of book and if author is Bobby B. then break the loop.
}
</code></pre><p>Since the&#xA0;<code>author</code>&#xA0;and the&#xA0;<code>title</code>&#xA0;variables are declared outside of the&#xA0;<code>for-of</code>&#xA0;loop, we can destructure them inside the loop by declaring new&#xA0;<code>author</code>&#xA0;and&#xA0;<code>title</code>&#xA0;variables with the&#xA0;<code>const</code>&#xA0;or the&#xA0;<code>let</code>&#xA0;keyword and thus shadowing the variables outside of the loop.</p><p>This is not quite what we want, however. Since we declared these two variables inside the loop now, we won&apos;t be able to access them after the loop.<br>When logging the variables we get&#xA0;<code>undefined</code>&#xA0;for both of them, as the destructured variables, declared inside the loop, have gone out of scope once the loop has finished.</p><p>Note, that if you used&#xA0;<code>var</code>&#xA0;to declare the destructured variables inside the loop you would once again get a &quot;SyntaxError: Identifier &apos;author&apos; has already been declared&quot;. This is because&#xA0;<code>var</code>&#xA0;variables are function level scoped in JavaScript, whereas&#xA0;<code>const</code>&#xA0;and&#xA0;<code>let</code>&#xA0;variables are block scoped.</p><p>Don&apos;t use&#xA0;<code>var</code>!</p><pre><code class="language-javascript">const books = [{}, {}, {}, {} ,{}, {author: &quot;Bobby. B&quot;, title: &quot;Ladida&quot;}, {}, {}, {}, {} ,{}];

let author;
let title;

for(let book of books ){
    const {author, title} = book;
    if(author === &quot;Bobby. B&quot;){
        break;
    }
}
console.log(author) // undefined
console.log(title) // undefined
</code></pre><h3 id="the-right-way-to-do-it">The right way to do it</h3><p>As mentioned above, when braces&#xA0;<code>{</code>&#xA0;appear as the beginning of a statement, they are interpreted as a block. When braces appear at later point in a statement, such as when beginning the statement with&#xA0;<code>const</code>,&#xA0;<code>let</code>&#xA0;or&#xA0;<code>var</code>&#xA0;(don&apos;t do it!), they are interpreted as an object.<br>So all we have to do is make it so that the braces do not appear first in the statement, while also not using&#xA0;<code>const</code>,&#xA0;<code>let</code>&#xA0;or&#xA0;<code>var</code>&#xA0;(seriously, don&apos;t).</p><p>How?<br>Wrap the entire line where the destructuring happens in parentheses&#xA0;<code>()</code>.</p><p>For our first code snippet we will get the following:</p><pre><code class="language-javascript">let author;
let title;

const book = {
    author: &quot;Bobby B.&quot;,
    title: &quot;Ladida&quot;
};

({author, title} = book);
</code></pre><p>And this is what our second snippet looks like after wrapping the desctructuring line in parentheses:</p><pre><code class="language-javascript">const books = [{}, {}, {}, {} ,{}, {author: &quot;Bobby. B&quot;, title: &quot;Ladida&quot;}, {}, {}, {}, {} ,{}];

let author;
let title;

for(let book of books ){
    ({author, title} = book);
    if(author === &quot;Bobby. B&quot;){
        break;
    }
}
console.log(author) // undefined
console.log(title) // undefined
</code></pre><p>When wrapping the entire line in parentheses, make sure to end the previous line with a semicolon. Otherwise, it might trigger a function invocation!</p>]]></content:encoded></item><item><title><![CDATA[Prototypes in JavaScript]]></title><description><![CDATA[<p><strong>TL;DR</strong>:&#xA0;<code>[[Prototype]]</code>&#xA0;is an internal property that exists on all JS objects. It can be accessed via the&#xA0;<code>__proto__</code>&#xA0;property.&#xA0;<code>.prototype</code>&#xA0;is an object which exists only on function constructors and is used to set a constructed object&apos;s internal&#xA0;<code>[[Prototype]</code></p>]]></description><link>https://celsiusnotes.com/prototypes-in-javascript/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1de</guid><category><![CDATA[programming]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Sat, 02 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p><strong>TL;DR</strong>:&#xA0;<code>[[Prototype]]</code>&#xA0;is an internal property that exists on all JS objects. It can be accessed via the&#xA0;<code>__proto__</code>&#xA0;property.&#xA0;<code>.prototype</code>&#xA0;is an object which exists only on function constructors and is used to set a constructed object&apos;s internal&#xA0;<code>[[Prototype]]</code></p><p>If you have ever been confused about all the different kinds of prototypes in JavaScript, you are not alone. This article is an overview and explanation of the different kinds of prototypes and their purposes in JavaScript.</p><h2 id="prototype"><code>[[Prototype]]</code></h2><p>In the ECMAScript specifications double brackets denote internal properties and are, according to the specs, not part of the ECMAScript language. This means that those internal properties are not accessible by the objects that contain them.</p><p><code>[[Prototype]]</code>&#xA0;is an internal property on all JS objects that points to the object&apos;s prototype. Every JS object has an internal&#xA0;<code>[[Prototype]]</code>. This goes for for objects created with object literals, those created with the&#xA0;<code>new</code>&#xA0;keyword and also for those created with&#xA0;<code>Object.create()</code>. Further, even function constructors have an internal&#xA0;<code>[[Prototype]]</code>.</p><h2 id="proto"><code>__proto__</code></h2><p>Since&#xA0;<code>[[Prototype]]</code>&#xA0;is an internal property it was never meant to be accessible by developers, according to the ECMA specs. At some point, however, browser vendors and other environments started giving access to the internal&#xA0;<code>[[Prototype]]</code>&#xA0;object via the&#xA0;<code>__proto__</code>&#xA0;property.<br>This means that&#xA0;<code>__proto__</code>&#xA0;and&#xA0;<code>[[Prototype]]</code>&#xA0;refer to the same thing.<br><code>__proto__</code>&#xA0;is simply a way to access the internal&#xA0;<code>[[Prototype]]</code>&#xA0;in some JS environments.</p><p>The internal&#xA0;<code>[[Prototype]]</code>&#xA0;is a regular JS object and thus also has an internal&#xA0;<code>[[Prototype]]</code>&#xA0;and so on. This goes all the way down to Object<code>.prototype</code>. The internal<code>[[Prototype]]</code>&#xA0;of Object<code>.prototype</code>&#xA0;is null. This is called the prototype chain. More on that later.</p><h2 id="prototype-1"><code>.prototype</code></h2><p>The&#xA0;<code>.prototype</code>&#xA0;property only exists on function constructors! When you define a function, the constructor is given an almost empty&#xA0;<code>.prototype</code>&#xA0;object for free. The only property on this object is&#xA0;<code>.constructor</code>, which points back to the function constructor, i.e.&#xA0;<code>.prototype</code>&#xA0;has a property&#xA0;<code>.constructor</code>&#xA0;and vice versa.</p><p>When you create a new object with the&#xA0;<code>new</code>&#xA0;keyword, its internal<code>[[Prototype]]</code>&#xA0;is set to the&#xA0;<code>.prototype</code>&#xA0;of the function constructor that was used to create the object.</p><h2 id="object-creation-prototype-chain">Object creation prototype chain</h2><p>Let&apos;s look at how the internal&#xA0;<code>[[Prototype]]</code>&#xA0;object is set when creating an object with the&#xA0;<code>new</code>&#xA0;keyword, as an object literal and with&#xA0;<code>Object.create()</code>.</p><h3 id="new-keyword">new keyword</h3><p>When you create a new object with the&#xA0;<code>new</code>&#xA0;keyword, that object&apos;s internal&#xA0;<code>[[Prototype]]</code>&#xA0;is set to the constructor function&apos;s&#xA0;<code>.prototype</code></p><pre><code class="language-javascript">function Car(){}
const mCar = new Car();
mCar.__proto__ === Car.prototype; // true
</code></pre><h2 id="object-literal">Object literal</h2><p>When you create a new object with the object literal syntax the object&apos;s internal&#xA0;<code>[[Prototype]]</code>&#xA0;is set to Object<code>.prototype</code>.</p><pre><code class="language-javascript">const obj = {};
obj.__proto__ === Object.prototype; // true
</code></pre><h2 id="object-create">Object Create</h2><p>When you create a new object with&#xA0;<code>Object.create()</code>, the internal [[Protoype]] of the created object is set to the object passed in as the first argument to&#xA0;<code>Object.create()</code>.</p><pre><code class="language-javascript">const car = {
    wheels: 4
};
const mCar = Object.create(car);
mCar.__proto__ === car // true
</code></pre><h3 id="prototype-chain">Prototype chain</h3><p>Since the internal&#xA0;<code>[[Prototype]]</code>&#xA0;object is simply that, an object, it too has an internal&#xA0;<code>[[Prototype]]</code>, which in turn, yada yada yada.<br>This leads to a prototype chain.</p><p>If a prototype is not specified for an object explicitly, then the default value for&#xA0;<code>__proto__</code>&#xA0;is taken:&#xA0;<code>Object.prototype</code>.<br><code>Object.prototype</code>&#xA0;itself also has a&#xA0;<code>__proto__</code>, which is the final link of the chain and is set&#xA0;<code>null</code>.</p><p>If a property or method isn&apos;t found on an object instance, the prototype chain is traversed. The first found property/method with the same name is used. If none is found in the entire chain, all the way down to Object.prototype, undefined is returned.</p><p>Properties in the prototype chain are called &apos;inherited properties&apos; as opposed to properties on the instances themselves which are &apos;own properties&apos;.</p>]]></content:encoded></item><item><title><![CDATA[JavaScript Template Literals and styled-components]]></title><description><![CDATA[<h3 id="template-literals">Template Literals</h3><p>Template literals in JavaScript are basically regular strings on roids. The syntax for writing them is with backticks `` instead of regular string quotes. You can place expressions into those template literals which will be evaluated and replaced with the resulting values of those expression.</p><pre><code class="language-javascript">const name = &apos;Celsius&</code></pre>]]></description><link>https://celsiusnotes.com/javascript-template-literals-and-styled-components/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1dd</guid><category><![CDATA[programming]]></category><category><![CDATA[javascript]]></category><category><![CDATA[react-native]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Fri, 01 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<h3 id="template-literals">Template Literals</h3><p>Template literals in JavaScript are basically regular strings on roids. The syntax for writing them is with backticks `` instead of regular string quotes. You can place expressions into those template literals which will be evaluated and replaced with the resulting values of those expression.</p><pre><code class="language-javascript">const name = &apos;Celsius&apos;;
`My name is ${name}. What&apos;s yours?` // My name is Celsius. What&apos;s yours?
</code></pre><p></p><p>Here is how the evaluation process of a template literal works:<br>The template literal is broken down into an array of strings and a list of variables. In the example above the array of strings would be&#xA0;<code>[ &apos;My name is &apos;, &apos;. What\&apos;s yours?&apos; ]</code>&#xA0;whereas the list of variables would consist only of the evaluated value of the&#xA0;<code>name</code>&#xA0;variable, which is &quot;Celsius&quot;.</p><p>Then, this array of strings and the list of evaluated values is passed to a function which can concatenate all those strings and return the phrase &quot;My name is Celsius. What&apos;s yours?&quot; That is in fact what the default function for template literals does. It simply concatenates the strings in the array, inserting the values of the evaluated expressions between them. A sample implementation of this default template literal function could look like this:</p><pre><code class="language-javascript">function defaultTemplateLiteralFunction(strings, ...values){
	return strings.reduce((acc, v, i) =&gt; {
		acc += v;
		acc += values[i] || &apos;&apos;;
		return acc;
	}, &apos;&apos;);
}

</code></pre><p>What this function does is simply concatenate the values from the strings array and the list of evaluated values alternatingly, starting with the list of strings.</p><h2 id="tagged-templates">Tagged Templates</h2><p>JavaScript let&apos;s you define your own function to process the arguments extracted from the template literal. If you write a function right before the template literal this function will be used to process the arguments extracted from the template literal by JavaScript. This is called a tagged template.</p><pre><code class="language-javascript">function tag(strings, ...values) {
	return `Hey ${values[0]}, nice to meet you. I am a tagged template :)`;
}

tag`My name is ${name}. What&apos;s yours?`; // Hey Celsius, nice to meet you. I am a tagged template :)
</code></pre><p>The above syntax can be thought of as invoking the tag function passing it the template literal (already processed into an array and values) as arguments.</p><p>Note, that tagged templates do not have to return strings! You can return any kind of value you like from your tagged templates. Yes, even a React component, which is really just a function anyway.</p><h2 id="using-tagged-templates">Using Tagged Templates</h2><p>You can use tagged templates anywhere you want to have more control over template literals and return different values based on the contents of the template literal.</p><p>One very popular library that uses template literals is the&#xA0;<a href="https://web.archive.org/web/20230208155556/https://www.styled-components.com/">styled-components</a>&#xA0;library for React and React Native applications. To create a simple styled&#xA0;<code>h1</code>&#xA0;component you could write something like the following:</p><pre><code class="language-javascript">const fontSize = calculateFontSize();
RedCenteredText = styled.h1`
	color: red;
	text-align: &apos;center;
	font-size: ${fontSize};
`
</code></pre><p>In this case&#xA0;<code>styled.h1</code>&#xA0;is a tagged template function, receiving the contents of the template literal. The template function parses the received CSS, replaces the placeholder variables with the appropriate values and returns an&#xA0;<code>H1</code>&#xA0;React component with the given styles.</p><p><code>RedCenteredText</code>&#xA0;is a React component which you could then use in your markup just like any other React component such as:</p><pre><code class="language-javascript">&lt;div&gt;
	&lt;RedCenteredText/&gt;
&lt;/div&gt;
</code></pre><p>So far, we&apos;ve only ever passed simple variables to be evaluated by the template literal. However, functions can also be passed as values to the template literal. If you have worked with the styled-components library before you will probably be familiar with how the following code snippet works:</p><pre><code class="language-javascript">RedOrWhiteCenteredText = styled.h1`
	color: ${props =&gt; props.error ? &apos;red&apos;, &apos;white&apos;};
	text-align: &apos;center;
	font-size: ${fontSize};
`
</code></pre><p>What happens here is that we are not only passing a variable but also a function to the template literal. The function processing the template literal will now return an H1 React component with either red or white text color depending on whether or not the&#xA0;<code>error</code>&#xA0;prop passed to that component is true.</p><h3 id="styled-html-elements">Styled HTML elements</h3><p>Let&apos;s try to work our way towards writing a tag function that takes a template literal with parametrized CSS and returns a React component whose styles adapt to the props passed to it.</p><p>Here is how you could write a sample&#xA0;<code>styled.div</code>&#xA0;tag function that takes in a string of CSS styles and returns&#xA0;<code>&lt;div&gt;</code>&#xA0;element with those given styles as inline styles.</p><pre><code class="language-javascript">const styled = {
    div: (strings, ...values) =&gt; {
        const styles = strings[0]
        .trim()
        .replace(/\n/gi, &quot;&quot;)
        .replace(/\s\s/gi, &quot;&quot;);        
        return `&lt;div style=&quot;${styles}&quot;&gt;&lt;/div&gt;`;
    }
}

const StyledDiv = styled.div`
    background-color: red;
    width: 50px;
    height: 50px;
    text-align: center;
`;

console.log(StyledDiv) 
//&lt;div style=&quot;background-color: red;width: 50px;height: 50px;text-align: center;&quot;&gt;&lt;/div&gt;

</code></pre><p>We remove all unnecessary whitespaces by trimming, replacing new lines and replacing double spaces with single spaces and then simply pass the resulting value as the contents of the&#xA0;<code>style</code>&#xA0;attribute to a&#xA0;<code>&lt;div&gt;</code>.</p><p>Now, what if we want to pass variables to the template literal? We make use of our&#xA0;<code>defaultTemplateLiteralFunction</code>&#xA0;defined above to preparse the parametrized styles into a string of temporary styles, which then undergoes the same treatment as the styles from our previous example:</p><pre><code class="language-javascript">function defaultTemplateLiteralFunction(strings, ...values){
	return strings.reduce((acc, v, i) =&gt; {
		acc += v;
		acc += values[i] || &apos;&apos;;
		return acc;
	}, &apos;&apos;);
	
}

const styled = {
    div: (strings, ...values) =&gt; {
        const tempStyles = defaultTemplateLiteralFunction(strings, ...values);
        const styles = tempStyles
        .trim()
        .replace(/\n/gi, &quot;&quot;)
        .replace(/\s\s/gi, &quot;&quot;);;
        return `&lt;div style=&quot;${styles}&quot;&gt;&lt;/div&gt;`;
    }
}

const red = &quot;green&quot;;
const size = &quot;75px&quot;;

const StyledDiv = styled.div`
    background-color: ${red};
    width: ${size};
    height: ${size};
    text-align: center;
`;

console.log(StyledDiv)
// &lt;div style=&quot;background-color: green;width: 75px;height: 75px;text-align: center;&quot;&gt;&lt;/div&gt;
</code></pre><p>Creating HTML elements with inline styles from tagged template literals is fun and all but doesn&apos;t really seem all that useful, as there is no way to use the generated HTML without some extra effort.</p><h3 id="styled-react-components">Styled React components</h3><p>Now let&apos;s figure out how to return a fully-fledged React component from a template literal function.</p><pre><code class="language-javascript">import React, { Component } from &quot;react&quot;;

/**
 * @function parseStyles
 * Parses a string of inline styles into a javascript object with casing for react
 * Source: https://gist.github.com/goldhand/70de06a3bdbdb51565878ad1ee37e92b
 *
 * @param {string} styles
 * @returns {Object}
 */
const parseStyles = styles =&gt;
  styles
    .split(&quot;;&quot;)
    .filter(style =&gt; style.split(&quot;:&quot;)[0] &amp;&amp; style.split(&quot;:&quot;)[1])
    .map(style =&gt; [
      style
        .split(&quot;:&quot;)[0]
        .trim()
        .replace(/-./g, c =&gt; c.substr(1).toUpperCase()),
      style.split(&quot;:&quot;)[1].trim()
    ])
    .reduce(
      (styleObj, style) =&gt; ({
        ...styleObj,
        [style[0]]: style[1]
      }),
      {}
    );

const styled = {
  div: (strings, ...values) =&gt; {
    return function(props) {
      function defaultTemplateLiteralFunction(strings, ...values) {
        return strings.reduce((acc, v, i) =&gt; {
          acc += v;
          if (!values[i]) {
            acc += &quot;&quot;;
            return acc;
          }

          acc += typeof values[i] === &quot;function&quot; ? values[i](props) : values[i];
          return acc;
        }, &quot;&quot;);
      }

      const tempStyles = defaultTemplateLiteralFunction(strings, ...values);
      const styles = tempStyles.trim().replace(/\n/gi, &quot;&quot;);
      if (!styles) {
        return null;
      }

      let parsedStyles = parseStyles(styles);
      return React.createElement(
        &quot;div&quot;,
        {
          ...props,
          style: parsedStyles
        },
        &quot;Hello&quot;
      );
    };
  }
};

const red = &quot;red&quot;;
const size = &quot;100px&quot;;

const StyledDiv = styled.div`
  background-color: ${red};
  width: ${props =&gt; (props.small ? size : size * 2)};
  height: ${props =&gt; (props.small ? size : size * 2)};
  text-align: center;
`;

class App extends Component {
  render() {
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;StyledDiv small /&gt;
        &lt;p className=&quot;App-intro&quot;&gt;
          To get started, edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.
        &lt;/p&gt;
      &lt;/div&gt;
    );
  }
}

export default App;


// If you take away the `small` prop it doesn&apos;t work since the multiplication of 100px * 2 returns NaN and I didn&apos;t feel like implementing px value times integer multiplication for this proof of concept.

</code></pre><p>So what&apos;s happening here? The&#xA0;<code>parseStyles</code>&#xA0;function takes a string of inline styles and parses them into a JS object with the correct casing (camelCase) so that these styles can be used within a React component. The code for this was taken from&#xA0;<a href="https://web.archive.org/web/20230208155556/https://gist.github.com/goldhand/70de06a3bdbdb51565878ad1ee37e92b">here</a>.</p><p>Our implementation for a&#xA0;<code>div</code>&#xA0;styled component now returns a React component, which is simply a function that returns a React element. Inside this function, we define&#xA0;<code>defaultTemplateLiteralFunction</code>&#xA0;with a slightly different implementation than above. Defining the function inside the functional component is done, so that the function captures the props which are passed to the React functional component.</p><p>When we now call</p><pre><code class="language-javascript">styled.div`
    style1:...
    style1:...
    etc.`
</code></pre><p>the passed styles are first processed just as before by concatenating the them into a single string, replacing the parametrized values. The crucial difference in this implementation of the&#xA0;<code>defaultTemplateLiteralFunction</code>&#xA0;is that if we detect a parametrized value to be a function, we call that function, passing it the props of the functional component.</p><p>At this point all parametrized values have been replaced and we have a string of styles in&#xA0;<code>tempStyles</code>. All that&apos;s left to is turn this string into a JS object so that it can be used as a React style object. The&#xA0;<code>parseStyles</code>&#xA0;function does just that.</p><p>Now that we have a proper JS style object we can create our React Element, passing it the parsed styles and returning it from our functional component.<br>Et voil&#xE1;, we have a poor man&apos;s implementation of div styled-components.</p>]]></content:encoded></item><item><title><![CDATA[How to make a drawer navigator with react-native-navigation]]></title><description><![CDATA[<p>In this tutorial we will build a drawer navigation for an imaginary e-commerce app with the React Native Navigation (RNN) library.<br>The first image below is what the finished drawer navigation will look like. The second one shows dribble shot that I used as design inspiration.</p><figure class="kg-card kg-image-card"><img src="https://web.archive.org/web/20230208161811im_/https://celsiusnotes.com/content/images/2018/08/output.png" class="kg-image" alt="output" loading="lazy" width="533" height="436"></figure><h2 id="about-react-native-navigation">About React Native Navigation</h2>]]></description><link>https://celsiusnotes.com/how-to-make-a-drawer-navigator-with-react-native-navigation/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1dc</guid><category><![CDATA[react-native]]></category><category><![CDATA[react-navigation]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Sun, 12 Aug 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>In this tutorial we will build a drawer navigation for an imaginary e-commerce app with the React Native Navigation (RNN) library.<br>The first image below is what the finished drawer navigation will look like. The second one shows dribble shot that I used as design inspiration.</p><figure class="kg-card kg-image-card"><img src="https://web.archive.org/web/20230208161811im_/https://celsiusnotes.com/content/images/2018/08/output.png" class="kg-image" alt="output" loading="lazy" width="533" height="436"></figure><h2 id="about-react-native-navigation">About React Native Navigation</h2><p>React Native Navigation is a native navigation library based on the underlying native navigation of the platform and is not a JavaScript based navigation solution like most other navigation libraries for React Native.</p><h3 id="installing-react-native-navigation">Installing React Native Navigation</h3><p>To install React Native Navigation simply follow the installation instructions give here for&#xA0;<a href="https://web.archive.org/web/20230208161811/https://wix.github.io/react-native-navigation/#/installation-android">Android</a>&#xA0;or here for&#xA0;<a href="https://web.archive.org/web/20230208161811/https://wix.github.io/react-native-navigation/#/installation-ios">iOS</a>.<br>Note, that this article was written using React Native Navigation version 1!</p><h2 id="getting-started">Getting Started</h2><p>To start an app with React Native Navigation you have to call either the static&#xA0;<code>startTabBasedApp</code>or the static&#xA0;<code>startSingleScreenApp</code>&#xA0;with the appropriate params object. We will be using the&#xA0;<code>startTabBasedApp</code>&#xA0;method for our drawer navigator example, since it naturally comes with support for tabs.</p><h3 id="simple-tab">Simple Tab</h3><p>To keep this simple and focused on the the drawer menu, we will be showing empty screens for every tab, with nothing but the screen title in the navigation bar. Let&apos;s create a&#xA0;<code>Tab</code>&#xA0;component right in our index.js file which will serve as the screen component to be shown for all drawer tabs.</p><pre><code class="language-javascript">const Tab = () =&gt; {
	return(
		&lt;View style={{ flex: 1, alignItems: &apos;center&apos;, justifyContent: &apos;center&apos; }}&gt;
			&lt;Text&gt;Tab Screen&lt;/Text&gt;
		&lt;/View&gt;
	)
}
</code></pre><h2 id="registering-screens">Registering Screens</h2><p>RNN requires you to register screens before showing them on screen. For that we create a&#xA0;<code>registerScreens()</code>&#xA0;function.</p><p>In that function we will register the components for all the screens we want to show on in our app. The RNN docs recommend choosing names which will be unique within the entire app, as your screens might end up being bundled with other packages. It is recommended to use the following naming convention&#xA0;<code>packageName.screenName</code>. So let&apos;s create a constant&#xA0;<code>packageName</code>&#xA0;and the&#xA0;<code>registerScreens()</code>&#xA0;function in our index.js file.</p><pre><code class="language-javascript">import { Navigation } from &apos;react-native-navigation&apos;;

const packageName = &apos;com.rnplayground&apos;;

function registerScreens(){
	Navigation.registerComponent(`${packageName}.Cart`, () =&gt; Tab );
	Navigation.registerComponent(`${packageName}.Wishlist`, () =&gt; Tab );
	Navigation.registerComponent(`${packageName}.Deals`, () =&gt; Tab );
	Navigation.registerComponent(`${packageName}.Browse`, () =&gt; Tab );
	Navigation.registerComponent(`${packageName}.SettingsTab`, () =&gt; Tab );
	Navigation.registerComponent(`${packageName}.DrawerScreen`, () =&gt; DrawerNavigatorContainer );
}
</code></pre><h2 id="defining-tabs">Defining Tabs</h2><p>The&#xA0;<code>Navigation.startTabBasedApp</code>&#xA0;method takes an object which has a tabs property, which excpects an array specifying all the tabs and their properties.</p><p>Let&apos;s create a function called&#xA0;<code>getTabConfig()</code>&#xA0;which returns the this tabs array.</p><pre><code class="language-javascript">function getTabConfig() {
	const tabs = [
		{
			screen: `${packageName}.Cart`,
			title: &apos;Shopping Cart&apos;,
			iconName: &apos;shopping-cart&apos;,
			iconColor: &apos;yellow&apos;,
			icon: require(&apos;./image.png&apos;),
			navigatorStyle: {
				tabBarHidden: true,
			},
		},
		{
			screen: `${packageName}.Wishlist`,
			title: &apos;Wishlist&apos;,
			iconName: &apos;favorite&apos;,
			iconColor: &apos;red&apos;,
			icon: require(&apos;./image.png&apos;),
			navigatorStyle: {
				tabBarHidden: true,
			},

		},
		{
			screen: `${packageName}.Deals`,
			title: &apos;Deals&apos;,
			iconName: &apos;money-off&apos;,
			iconColor: &apos;orange&apos;,
			icon: require(&apos;./image.png&apos;),
			navigatorStyle: {
				tabBarHidden: true,
			},

		},
		{
			screen: `${packageName}.Browse`,
			title: &apos;Browse&apos;,
			iconName: &apos;search&apos;,
			iconColor: &apos;green&apos;,
			icon: require(&apos;./image.png&apos;),
			divider: true,
			navigatorStyle: {
				tabBarHidden: true,
			},
		},
		{
			screen: `${packageName}.SettingsTab`,
			title: &apos;Settings&apos;,
			iconName: &apos;settings&apos;,
			iconColor: &apos;grey&apos;,
			icon: require(&apos;./image.png&apos;),
			navigatorStyle: {
				tabBarHidden: true,
			},
		},
	];

	return tabs;
}
</code></pre><p>If you take a look at the documentation for&#xA0;<code>startTabBasedApp</code>&#xA0;<a href="https://web.archive.org/web/20230208161811/https://wix.github.io/react-native-navigation/#/top-level-api?id=starttabbasedappparams">here</a>, you&apos;ll notice that the&#xA0;<code>iconName</code>,&#xA0;<code>iconColor</code>&#xA0;and the&#xA0;<code>divider</code>&#xA0;(in the Browse tab object) properties are nowhere to be found. That&apos;s because they are not part of RNN. I just added those myself, because we&apos;ll need those values later on.</p><p>The&#xA0;<code>screen</code>&#xA0;property specifies which component will be shown when you tap on that tab. The&#xA0;<code>title</code>&#xA0;property defines the name that will show up in the navigation bar. While we won&apos;t be using the&#xA0;<code>icon</code>&#xA0;attribute, it is required by RNN for every tab object. We just give it the value of a random image.png image, which is in the same directory as the index.js file.</p><p>The&#xA0;<code>navigatorStyle</code>&#xA0;object allows you to style your navigator. We only make use of the&#xA0;<code>tabBarHidden</code>&#xA0;attribute for now, by setting it to&#xA0;<code>true</code>&#xA0;in every tab.</p><h2 id="starting-the-app">Starting the App</h2><p>Now that we&apos;ve defined our tabs it&apos;s almost time to start the app for the first time. We&apos;re close, I promise. Let&apos;s create a function called&#xA0;<code>startApp()</code>&#xA0;in the index.js file in which we register the screens, get the tab configurations and then call&#xA0;<code>Navigator.startTabBasedApp()</code>, passing the tabs and a few other options.</p><p>The&#xA0;<code>drawer</code>&#xA0;property let&apos;s us specify a drawer with all its properties and settings. We want a left drawer, which is why we define the&#xA0;<code>left</code>&#xA0;property of the drawer object. In it we define the screen, which will be rendered as the left drawer and also get to define props that will get passed to the drawer when the app is started. The contents of the&#xA0;<code>passProps</code>&#xA0;object will be available as regular props in the drawer component. We pass the tabs array, an&#xA0;<code>activeIndex</code>&#xA0;attribute set to 0 and the&#xA0;<code>profileInfo</code>&#xA0;object.</p><p>In order to make the tab bar not show at the bottom of the screen, we also set the&#xA0;<code>tabBarHidden</code>&#xA0;property of the&#xA0;<code>tabStyle</code>&#xA0;object in the&#xA0;<code>drawer</code>&#xA0;object to true.</p><pre><code class="language-javascript">function startApp() {
  
	registerScreens();
    
	const tabs = getTabConfig();

	const profileInfo = {
		firstName: &apos;Celsius&apos;,
		lastName: &apos;W.&apos;,
		imgSource: require(&apos;./image.png&apos;)
	}
    
	Navigation.startTabBasedApp(
		{
		tabs: tabs,
		drawer: { 
			left: {
			screen: `${packageName}.DrawerScreen`, // unique ID registered with Navigation.registerScreen
			passProps: {
				tabs: tabs,
				activeTabIndex: 0,
				profileInfo: profileInfo

			},
			fixedWidth: 800,
			}
		},
		tabsStyle:{
			tabBarHidden: true,
		}
		},
	);
  
  }
</code></pre><h3 id="drawernavigator-class">DRAWERNAVIGATOR CLASS</h3><p>Before we move on to the&#xA0;<code>DrawerNavigatorContainer</code>, the centerpiece of this tutorial, let&apos;s first take a look at two other components that we will use inside the&#xA0;<code>DrawerNavigatorContainer</code>: the&#xA0;<code>DrawerProfileContainer</code>&#xA0;and the&#xA0;<code>DrawerItem</code>&#xA0;component.</p><p>The&#xA0;<code>DrawerProfileContainer</code>&#xA0;component houses the profile image and the name of the user. The&#xA0;<code>DrawerItem</code>&#xA0;component is a pressable component representing all the tabs that we can navigate to. It has a icon and a label.</p><pre><code class="language-javascript">export default DrawerProfileContainer = (props) =&gt; {

    const {source, firstName, lastName, containerStyle} = props;
    const iconProps = source ? {source: source} : {icon: {name: &apos;account-circle&apos;}}

    return(
        &lt;View style={[styles.container, containerStyle]}&gt;
            &lt;Avatar
                width={80}
                height={80}
                activeOpacity={0.7}	
                rounded={true}
                containerStyle={styles.avatar}
                {...iconProps}
            /&gt;
            &lt;Text
                style={styles.nameText}&gt;
                {firstName} {lastName}
            &lt;/Text&gt;
        &lt;/View&gt;
    );


}

export default DrawerItem = (props) =&gt; {
    const {label, iconName, iconColor, isActive} = props;
    const containerStyles = isActive ? [styles.container, styles.containerActive] : [styles.container]
    return (
        &lt;TouchableOpacity onPress={props.onPress}
            underlayColor=&apos;blue&apos;&gt;
            &lt;View style={containerStyles}&gt;
                {isActive &amp;&amp; 
                    &lt;View style={styles.leftBar}/&gt;
                }

                &lt;Icon name={iconName}
                    color={iconColor || &apos;white&apos;}
                    size={24}
                    containerStyle={styles.icon}
                /&gt;
                &lt;Text style={styles.label}&gt;
                    {label}
                &lt;/Text&gt;
            &lt;/View&gt;
        &lt;/TouchableOpacity&gt;
    );
}
</code></pre><p>Following is the code for the&#xA0;<code>DrawerNavigationContainer</code>&#xA0;component. This is the component that describes the look and behavior of the drawer.</p><p>In the&#xA0;<code>render()</code>&#xA0;method we return&#xA0;<code>DrawerProfileContainer</code>. We also iterate over the&#xA0;<code>tabs</code>&#xA0;prop that we passed via the&#xA0;<code>passProps</code>&#xA0;when we called&#xA0;<code>Navigation.startTabBasedApp()</code>&#xA0;above. From each item in that array we create a&#xA0;<code>DrawerItem</code>&#xA0;element, passing the&#xA0;<code>navigationItemPressed()</code>&#xA0;method as the&#xA0;<code>onPress</code>&#xA0;prop. When a&#xA0;<code>DrawerItem</code>&#xA0;receives a press, the navigator is told to switch to the tab specified by the&#xA0;<code>DrawerItems&apos;s</code>&#xA0;index and then toggle the drawer to close it. We also have to set our&#xA0;<code>activeTabIndex</code>&#xA0;state to the new index, which is exactly what we do.</p><p>You&apos;ll notice that there is also a&#xA0;<code>Divider</code>&#xA0;component that we render after the&#xA0;<code>DrawerItem</code>&#xA0;if the&#xA0;<code>divider</code>&#xA0;attribute on the current tab is a truthy value. What gives? If you take a look at the 4th tab in the&#xA0;<code>tabs</code>&#xA0;array in&#xA0;<code>getTabConfig</code>&#xA0;you&apos;ll see that is has a&#xA0;<code>divider</code>&#xA0;property. This is not a property provided by React Native Navigation, but one that I added so that when I rendered the drawer items, I could tell the&#xA0;<code>DrawerNavigationContainer</code>&#xA0;to render a divider after every&#xA0;<code>DrawerItem</code>&#xA0;component associated with a tab with a truthy&#xA0;<code>divider</code>&#xA0;property.</p><p>While we&apos;re on the subject of properties not provided by React Native Navigation, it should also be mentioned that the&#xA0;<code>iconColor</code>&#xA0;and&#xA0;<code>iconName</code>&#xA0;properties are also not from React Native Navigation. I added those, so that I could tell the&#xA0;<code>DrawerItems</code>&#xA0;which icons to render in which colors next to the labels. The icons are material icons from the&#xA0;<a href="https://web.archive.org/web/20230208161811/https://github.com/react-native-training/react-native-elements">react-native-elements</a>&#xA0;library.</p><pre><code class="language-javascript">export default class DrawerNavigationContainer extends React.Component {

        state = {
            activeTabIndex: 0
        }

        navigationItemPressed = (route, index) =&gt; {
            action(`Should go to screen ${route.label} and close drawer.`)

            this.props.navigator.switchToTab({
                tabIndex: index,
            });
            this.props.navigator.toggleDrawer({
                side: &apos;left&apos;,
                to: &apos;closed&apos;,
                animated: &apos;true&apos;,
            });

            this.setState({
                activeTabIndex: index
            });
        }

        render(){
            const {tabs, profileInfo} = this.props;
            const {imgSource, ...rest} = profileInfo;

            if (!tabs) {
                return null;
            } else {
                return (
                    &lt;View style={styles.container}&gt;

                        &lt;DrawerProfileContainer
                            source={imgSource}
                            {...rest}

                        /&gt;

                        &lt;View style={styles.navigationContainer}&gt;
                            {tabs.map((route, index) =&gt; {
                                const navigationLabel = route.title;
                                const navigationIconName = route.iconName;
                                const iconColor = route.iconColor;

                                return (
                                    &lt;React.Fragment key={route.screen}&gt;
                                        &lt;DrawerItem
                                            label={navigationLabel}
                                            iconName={navigationIconName}
                                            isActive={this.state.activeTabIndex === index}
                                            iconColor={iconColor}
                                            onPress={() =&gt; {this.navigationItemPressed(route, index)}}
                                        &gt;
                                        &lt;/DrawerItem&gt;
                                        {route.divider &amp;&amp; &lt;Divider style={styles.divider} /&gt; }
                                    &lt;/React.Fragment&gt;
                                );
                            })}
                        &lt;/View&gt;
                    &lt;/View&gt;


                );
            }	

        }
    }
</code></pre><p>That&apos;s it. You should now have a drawer navigator if you compile and run the code on a device or an emulator.</p><p>You can check out the code for this article on github&#xA0;<a href="https://web.archive.org/web/20230208161811/https://github.com/Billydubb/monorepo/tree/master/DrawerNavigatorExample">here</a>.</p><p>If you have any questions or comments, get in touch via&#xA0;<a href="https://web.archive.org/web/20230208161811/https://twitter.com/kelsiusdeg">twitter</a>&#xA0;or shoot me an&#xA0;<a href="https://web.archive.org/web/20230208161811/mailto:celsiuswilliams@gmail.com">email</a>.</p>]]></content:encoded></item><item><title><![CDATA[React Native 0.56 release]]></title><description><![CDATA[<p>React Native version 0.56 was recently released. Here is a selection of some changes to be excited about.</p><h2 id="support-for-babel-7-and-optional-chaining">Support for Babel 7 and optional chaining</h2><p>With React Native 0.56 comes support for Babel 7. If you are a Swift developer you will probably already be familiar with optional</p>]]></description><link>https://celsiusnotes.com/react-native-0-56-release/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1db</guid><category><![CDATA[programming]]></category><category><![CDATA[react-native]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 11 Jul 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>React Native version 0.56 was recently released. Here is a selection of some changes to be excited about.</p><h2 id="support-for-babel-7-and-optional-chaining">Support for Babel 7 and optional chaining</h2><p>With React Native 0.56 comes support for Babel 7. If you are a Swift developer you will probably already be familiar with optional chaining.<br>Optional chaining allows you to access nested properties of an object without having to worry about undefined intermediate objects.</p><p>Let&apos;s say we have an object like this:</p><pre><code class="language-javascript">const house = {
	apartment: {
		tenant: {
			name: &apos;Peter&apos;
		}
	}
}
</code></pre><p>Without optional chaining we would have to write something like this to access the nested&#xA0;<code>name</code>&#xA0;property of the&#xA0;<code>house</code>&#xA0;object:</p><pre><code class="language-javascript">let name = &quot;&quot;;
if(house &amp;&amp; house.apartment &amp;&amp; house.apartment.tenant &amp;&amp; house.apartment.tenant.name){
	name = house.apartment.tenant.name
}
</code></pre><p>Now with optional chaining we can try to access the name of the tenant without having to resort to querying each nested subproperty of house for&#xA0;<code>undefined</code>&#xA0;by simply writing:</p><pre><code class="language-javascript">const name = house?.apartment?.tenant?.name;
</code></pre><p>This line of code means:</p><p>If&#xA0;<code>house</code>&#xA0;is not undefined, evaluate&#xA0;<code>house.apartment</code>&#xA0;if&#xA0;<code>house.apartment</code>&#xA0;is not undefined evaluate&#xA0;<code>house.apartment.tenant</code>&#xA0;and if&#xA0;<code>house.apartment.tenant</code>&#xA0;is not undefined evaluate the value of&#xA0;<code>house.apartment.tenant.name</code>&#xA0;and assign it to&#xA0;<code>name</code>.</p><p>You can also mix optional chaining with normal chaining such as</p><pre><code class="language-javascript">const name = house?.apartment.tenant?.name;
</code></pre><p>This line means:</p><p>If&#xA0;<code>house</code>&#xA0;is not undefined, evaluate&#xA0;<code>house.apartment</code>&#xA0;and if&#xA0;<code>house.apartment.tenant</code>&#xA0;is not undefined, evaluate and assign the value of&#xA0;<code>house.apartment.tenant.name</code>&#xA0;to&#xA0;<code>name</code>.</p><p>Optional chaining is some nice syntactical sugar that allows you to write less code when accessing nested properties of an object. It also works with functions:</p><pre><code class="language-javascript">function identifyYourself() {
	return &apos;I am a function&apos;
}

identifyYourself?.() // returns &apos;I am a function&apos;
</code></pre><h2 id="flex-wrap-reverse">Flex wrap-reverse</h2><p>Up until now&#xA0;<code>flexWrap: wrap-reverse</code>&#xA0;hadn&apos;t been implemented in React Native.&#xA0;<code>flexWrap</code>&#xA0;let&apos;s us specify wrapping behavior of flex elements. The default is&#xA0;<code>nowrap</code>. This means that when the elements are bigger than the row (or column) in which they are aligned, they will shrink according to their flex values without wrapping into the next row.<br>| 1 || 2 || 3 |</p><p>Specifying&#xA0;<code>wrap</code>&#xA0;tells Flexbox to wrap the elements into the next row (or column) if they are too big, so that they can retain their original sizes.<br>| 1 || 2 |<br>| 3 |</p><p>The&#xA0;<code>wrap-reverse</code>&#xA0;value is similar to&#xA0;<code>wrap</code>&#xA0;as it wraps the elements to the next row (or, yes you guessed it, column). However, on top of wrapping to the next column (or row; see what I did there? &#x1F601;), it also reverses the direction from which the elements are wrapped. Or more precisely in Flexbox parlance: &apos;<code>cross-start</code>&#xA0;and&#xA0;<code>cross-end</code>&#xA0;are swapped.<br>| 3 |<br>| 2 || 1 |</p><ul><li><code>Image.defaultSource</code>&#xA0;property on Android<ul><li>Allows you to set a local placeholder image while loading a remote image. This had already been implemented in iOS.</li></ul></li><li><code>Image.resizeMode=repeat</code>&#xA0;on Android<ul><li>Implements the repeat value for the&#xA0;<code>resizeMode</code>&#xA0;prop for the&#xA0;<code>Image</code>&#xA0;component. This also already existed on iOS.</li></ul></li><li>From now on the minimum required version of Node will be version 8. With this change trailing commas, which Prettier adds to function parameter lists, are now allowed.</li><li>Xcode 9 and iOS 9 will now be the the minimum required versions for working with React Native 0.56</li><li>Android projects are now compiled with the SDK 26.</li></ul><h2 id="other-noteworthy-updates">Other noteworthy updates</h2><ul><li><code>Image.defaultSource</code>&#xA0;property on Android<ul><li>Allows you to set a local placeholder image while loading a remote image. This had already been implemented in iOS.</li></ul></li><li><code>Image.resizeMode=repeat</code>&#xA0;on Android<ul><li>Implements the repeat value for the&#xA0;<code>resizeMode</code>&#xA0;prop for the&#xA0;<code>Image</code>&#xA0;component. This also already existed on iOS.</li></ul></li><li>From now on the minimum required version of Node will be version 8. With this change trailing commas, which Prettier adds to function parameter lists, are now allowed.</li><li>Xcode 9 and iOS 9 will now be the the minimum required versions for working with React Native 0.56</li><li>Android projects are now compiled with the SDK 26.</li></ul>]]></content:encoded></item><item><title><![CDATA[First Class, Higher Order Functions, Closures and Lambdas. What's What?]]></title><description><![CDATA[<p>When first learning about functional programming the terms first-class function, higher-order function, closure and lambda are sure to come up. Those terms and concepts can be somewhat confusing to a functional programming novice. In this article I will try to shed some light on what each term means and how</p>]]></description><link>https://celsiusnotes.com/first-class-higher-order-functions-closures-and-lambdas-whats-what/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1da</guid><category><![CDATA[programming]]></category><category><![CDATA[functional-programming]]></category><category><![CDATA[computer-science]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 17 Jan 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>When first learning about functional programming the terms first-class function, higher-order function, closure and lambda are sure to come up. Those terms and concepts can be somewhat confusing to a functional programming novice. In this article I will try to shed some light on what each term means and how they are related.</p><h3 id="first-class-function">First-class function</h3><p>Programming languages that support first-class functions allow functions to be passed as arguments to other functions and returned as values from them. First-class functions can also be assigned to variables. In essence, a language supports first-class functions if it treats functions as regular values. That&#x2019;s really all there is to first-class functions. Pretty simple right?</p><p>Here are some examples of what you can do in languages that support first-class functions:</p><pre><code class="language-javascript">//Declare a function that takes a variable of type `Function` as a parameter
function myFunction(b: Function)
//Return a function return value from another function
function myFunction() {
&#x2026;

return function(){
	&#x2026;
}

}
//Assign a function to a variable
var f = function () {&#x2026;}
</code></pre><p></p><p>The most common example of the usefulness of first-class functions is the <code>map()</code> function. The <code>map()</code> function takes some collection <code>c</code> and a function <code>f</code> as parameters. The function f in turn takes an element of the same type as the elements contained in the collection <code>c</code> (It can also take an index and other arguments in some cases). The <code>map()</code> function then returns a new collection <code>d</code> which is simply the result of applying the function <code>f</code> to every element of the original collection <code>c</code>. Other common examples for first class functions are <code>reduce()</code> and <code>filter()</code>.</p><h3 id="higher-order-function">Higher-order function</h3><p>Higher-order functions are simply functions that take one or more functions as arguments or return a function as a result (the function has to do at least one of those things to be considered a higher-order function). A function that does neither of those things is called a first-order function (not to be confused with first-class function!).<br>The concept of a higher-order function also exists in Mathematics, where the differential operator is a higher-order function, as it accepts a function and returns it&apos;s derivative, which is also a function.</p><pre><code class="language-javascript">function higherOrderFunction(a: Function) {
&#x2026;
return function() {&#x2026;}

</code></pre><p></p><h3 id="closures">Closures</h3><p>A Closure is a type of first-class function. It is a function that captures or closes over its enclosing lexical scope. What does that mean? It means, that if you define a function and use variables inside that function that you have declared somewhere outside of that function, a closure will hold on to the references that point to those values, so that they still exist and can accessed even when the enclosing scope in which they where first declared no longer exists. Variables declared within the scope of the nested function are also called bound variables, while variables declared outside of the scope are free variables.</p><h4 id="whats-the-point">What&apos;s the point?</h4><p>This can be useful when you define a nested function within a function and return that nested function as return value of the outer function assigning it to a variable. Once the outer function has returned, it will be gone along with all its declared variables. But what about the returned nested function that was assigned to a variable? That function will still have access to the values of the variables declared in the outer function, even though the outer function is gone. This is referred to as capturing those variables or closing over them, hence the name.</p><h4 id="but-how">But how?</h4><p>The way you can picture a closure in memory, is as a struct or an object holding references over which it closed and also including a function or a pointer to the function code. Wikipedia puts it well by stating that a closure is a &#x2018;function together with an environment&#x2019;.</p><p>When a closure is created, it stores references to all the free variables of its enclosing scope which it needs; sort of like a snapshot. This kind of makes sense for global variables which aren&apos;t declared in functions, but what about variables inside functions, which live on the stack. Shouldn&apos;t they cease to exist as soon as the enclosing function returns and its frame is popped from the stack? Well, languages with support for closures don&apos;t (usually) implement the call stack with an actual stack data structure. Instead, the call stack is implemented as a linked list on the heap (go figure). When a function returns, its node is removed from the list. If a closure has any references to variables on any frame, it simply keeps a reference to the node in question.</p><p>To make everything clearer, let&#x2019;s look at an example:</p><pre><code class="language-javascript">function outer(a) {
return function increment() {
++a;
}
}
</code></pre><p></p><p>The outer function takes one argument and simply returns an inner function. The only thing the inner function does is to increment the value of the outer functions only parameter a. As soon as the outer function is called and its return value is assigned to incrementFromTen a closure is created, capturing a reference to the outer functions argument, which in this case happens to have a value of 10. Repeatedly calling incrementFromTen() will increment the captured value of a which has been captured by the closure, even though outer() has long returned.</p><h3 id="lambdas">Lambdas</h3><p>A lambda is simply a function an anonymous function. Lambdas are often used as one off function arguments for higher-order functions.</p>]]></content:encoded></item><item><title><![CDATA[Notes: Anatomy of an index and slow indexes]]></title><description><![CDATA[<p>Here are some of my notes from reading <a href="http://use-the-index-luke.com/?ref=celsiusnotes.com">&quot;What every developer should know about SQL performance&quot;</a>.</p><h2 id="anatomy-of-an-index">Anatomy of an Index</h2><ul><li>An index is pure redundancy. Just like the index in a book where everything in the book is listed and refers to the page on which you find</li></ul>]]></description><link>https://celsiusnotes.com/notes-anatomy-of-an-index-and-slow-indexes/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1d9</guid><category><![CDATA[databases]]></category><category><![CDATA[sql]]></category><category><![CDATA[computer-science]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Wed, 17 Jan 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Here are some of my notes from reading <a href="http://use-the-index-luke.com/?ref=celsiusnotes.com">&quot;What every developer should know about SQL performance&quot;</a>.</p><h2 id="anatomy-of-an-index">Anatomy of an Index</h2><ul><li>An index is pure redundancy. Just like the index in a book where everything in the book is listed and refers to the page on which you find it.</li><li>A node consist of the value of the indexed column and the row id of the record.</li><li>An index entry points to the location of the entry of the in the table, in which rows are completely unsorted, by means of row id.<ul><li>Row is actually the physical location of the row inside that table (which is simply a file or several). It is the fastest way to locate that row (even faster than primary key, since primary key is nothing more than an index itself.)</li></ul></li><li>An index is a B-Tree (not always, there are also other indexes) with the leaf nodes connected as a doubly linked list.<ul><li>The B-Tree can be searched by tree traversal and then the doubly linked list must be walked down by visiting one element after another.</li></ul></li><li>The keys of the leaf node elements are the values of the colums that is being indexed.</li></ul><h2 id="slow-indexes">Slow Indexes</h2><ul><li>Index traversal has 3 steps:<ul><li>1 tree traversal</li><li>2 following leaf node chain</li><li>3 accessing table data</li></ul></li><li>First ingredient to slow index is the leaf node chain, where the database must not only traverse the B-tree but then also must walk through all the leaf nodes in the linked list to see if there are more matching entries.</li><li>Second ingredient is accessing the table. The actual corresponding table data to a leaf node is usually scattered across many table blocks. That means, for every hit, there is a table access.</li></ul><p>Three ways of accessing and index:</p><ul><li>Index Unique Scan: Performs tree traversal only. Used if there is a unique constraint in the query making sure that only one entry will match</li><li>Index Range Scan: Tree traversal and then follows the leaf node chain to find all matching entries. Used if multiple entries could match the query.<ul><li>Can potentially read large parts of an index. Makes the query slow if many entries will have to be accessed with table access afterwards.</li></ul></li><li>Table Access by Index RowId: Retrieves the actual row from table. This is usually done for every matched entry after an index scan (the ones above) operation.</li></ul>]]></content:encoded></item><item><title><![CDATA[React Native: Implementing an AES encryption module for Android]]></title><description><![CDATA[<p>For an app I am currently working on I had to find a way to encrypt sensitive user data due to data security laws that the app has to abide by.<br>For iOS devices you don&apos;t have to worry about doing much yourself as the developer since they</p>]]></description><link>https://celsiusnotes.com/react-native-implementing-an-aes-encryption-module-for-android/</link><guid isPermaLink="false">65eabea2d42a4565dc31f1d8</guid><category><![CDATA[react-native]]></category><category><![CDATA[android]]></category><category><![CDATA[aes]]></category><dc:creator><![CDATA[Kelvin Williams]]></dc:creator><pubDate>Tue, 09 Jan 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>For an app I am currently working on I had to find a way to encrypt sensitive user data due to data security laws that the app has to abide by.<br>For iOS devices you don&apos;t have to worry about doing much yourself as the developer since they come with hardware level encryption. However, it&apos;s a different story for Android devices. While some devices do offer hardware encryption facilities, not all do. And when they do, it is not a guaranteed that the feature is enabled, since it&apos;s the users and not the developers who control that setting.</p><p>Since we use Realm for persistent storage in the app, which offers AES encryption with a 32 byte key, I chose to also use the same for encrypting non-database data such as user images and attachment files.</p><p>We&apos;re using React Native to create the app, which is why I hoped to find a preexisting React Native library that I could use. Unfortunately I couldn&apos;t find anything that actually worked the way I needed it to work, so I decided to write my own native module. Using a plain JavaScript crypto implementation was also not an option, as those are typically very slow, which would be problematic as there is a fair amount of encrypting and decrypting of data in the app.</p><h2 id="native-java-code">Native Java code</h2><p>These are the two methods for encrypting and decrypting a Base64 String input using the <a href="http://rtyley.github.io/spongycastle/?ref=celsiusnotes.com">spongycastle</a> crypto library.</p><pre><code class="language-java">
@ReactMethod
    public void getRandomIv(Promise promise){
        SecureRandom rng = new SecureRandom();
        byte[] ivBytes = new byte[16];
        rng.nextBytes(ivBytes);
    String ivBase64 = Base64.encodeToString(ivBytes, Base64.NO_WRAP);
    promise.resolve(ivBase64);
}

@ReactMethod
public void encryptSpongy(byte[] key, String clearText, String ivBytesBase64, Promise promise)
{
try
{
byte[] clear = clearText.getBytes(&quot;UTF-8&quot;);
byte[] ivBytes= Base64.decode(ivBytesBase64, Base64.NO_WRAP);
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), ivBytes));
        byte[] outBuf   = new byte[cipher.getOutputSize(clear.length)];

        int processed = cipher.processBytes(clear, 0, clear.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        byte[] outBuf2 = new byte[processed + 16];        // Make room for iv
        System.arraycopy(ivBytes, 0, outBuf2, 0, 16);    // Add iv
        System.arraycopy(outBuf, 0, outBuf2, 16, processed);    // Then the encrypted data

        final String encryptedB64 = Base64.encodeToString(outBuf2, Base64.NO_WRAP);

        //System.out.println(encryptedB64);

        promise.resolve(encryptedB64);

        //return encryptedB64;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

@ReactMethod
public void decryptSpongy(byte[] key, String encryptedBase64, Promise promise)
{
try
{
final byte[] encrypted = Base64.decode(encryptedBase64, Base64.NO_WRAP);
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        byte[] ivBytes = new byte[16];
        System.arraycopy(encrypted, 0, ivBytes, 0, ivBytes.length); // Get iv from data
        byte[] dataonly = new byte[encrypted.length - ivBytes.length];
        System.arraycopy(encrypted, ivBytes.length, dataonly, 0, encrypted.length   - ivBytes.length);

        cipher.init(false, new ParametersWithIV(new KeyParameter(key), ivBytes));
        byte[] clear = new byte[cipher.getOutputSize(dataonly.length)];
        System.out.println(cipher.getOutputSize(dataonly.length));
        int len = cipher.processBytes(dataonly, 0, dataonly.length, clear,0);
        len += cipher.doFinal(clear, len);


        final String decryptedString = new String(clear).substring(0, len);
        System.out.println(decryptedString);

        promise.resolve(decryptedString);


        //return decryptedString;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}    

</code></pre><p></p><p>The <code>getRandomIV()</code> method simply generates a random 16 byte initialization vector (IV) for the AES cipher and returns it as a Base64 encoded string.</p><p>In the <code>encrypt()</code> method<br><code>new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()))</code> means that we want to use the CBC mode of the AES cipher with padding. The padding mode used by default is PKCS7.<br>In the following lines the cipher is applied to the byte array of the input string and written into <code>outBuf</code>, after which the initiazation vector and the cipher are both copied into <code>outBuf2</code>. Finally, the cipher is encoded into a Base64 string and resolved as the result of a promise.</p><p>The <code>decrypt()</code> method simply reverses what happend in the <code>encrypt()</code> method, as AES is a symmetric cipher. Since the method expects the Base64 representation of the cipher instead of the actual cipher, we first have to decode it to retrieve the byte array on which the decryption algorithm will operate. Next we extract the initialzation vector and the encrypted data into separate byte arrays. After that, the same approach is used for decrypting the data that was used for encrypting it. The decrypted cleartext is stored in the <code>clear</code> variable.</p><p>Since we&apos;re using padding and AES is a block cipher which works on blocks of 16 bytes, the resulting cipher and also the cleartext obtained from decrypting will always be a multiple of 16 bytes.<br>This is why we have to extract the original cleartext in the <code>decrypt()</code> method from the result of applying the algorithm to the cipher. This is what happens here:<br><code>new String(clear).substring(0, len);</code>. The <code>len</code> variable is the amount of bytes in the resulting cleartext which are not padding.</p><h2 id="takeaways-and-things-i-relearned-in-the-process-of-implementing-this-module">Takeaways and things I (re)learned in the process of implementing this module</h2><ul><li>AES is a block cipher. This means it takes a plaintext of x bytes and encrypts it in blocks of y bytes. The resulting cipher will have a size that is a multiple of the blocksize y.</li><li>AES requires a random initialization vector with the same size as the blocksize.</li><li>In AES the block size is 16 bytes.</li><li>If the last block of data is less than 16 bytes long it has to be padded, so that the algorithm can work with 16 bytes.</li><li>The size of a cipher from a plaintext with length x is calculated as (x/16 +1)*16 (the division is an integer division).<ul><li>i.e. for x = 15 the cipher size is 16</li></ul></li><li>This results in cleartext lengths smaller than a multiple of 16 being rounded up to the next higher multiple and lengths which are an exact multiple of 16 also being rounded up, which results in getting a complete 16 bytes of padding.</li><li>It is common to store the IV together with the ciphertext which results in an additional 16 bytes.</li><li>AES can use 3 different key sizes: 128, 192 and 256 bits. The algorithm automatically changes the number of iterations based on the key size used. You don&apos;t have to specify the key size, you simply enter the key of one of those three sizes and the algorithm will automatically use the correct number of iterations.</li></ul>]]></content:encoded></item></channel></rss>