Category Archives: javascript

Currying and Partial Functions (js)

ref – https://hackernoon.com/currying-in-js-d9ddc64f162e
https://codeburst.io/currying-in-javascript-ba51eb9778dc
https://blog.bitsrc.io/understanding-currying-in-javascript-ceb2188c339

Partial Functions

ref – https://medium.com/@JosephJnk/partial-function-application-in-javascript-and-flow-7f3ca87074fe

Partial application is the act of taking a function which takes multiple arguments, and “locking in” some of those arguments, producing a function which takes fewer arguments. For instance, say we have this function:

base ^ exponent

This is partial application: we create square by making a new function, which just passes its arguments through to another function, adding some hard-coded arguments to that other function.

you can go one step further and create a partialApply function.

Now, some might begin to think that the number of nested functions a curried function has depends on the number of arguments it receives. Yes, that makes it a curry.

I can design the curried function of volume to be this:

So it can be called like this:

const hCy = volume(70);
hCy(203,142);
hCy(220,122);
hCy(120,123);

or

volume(70)(90,30);
volume(70)(390,320);
volume(70)(940,340);

We just defined a specialized function that calculates a volume of any cylinder of length (l), 70.

It expects 3 arguments and has 2 nested functions, unlike our previous version that expects 3 arguments and has 3 nesting functions.

This version isn’t a curry. We just did a partial application of the volume function.

Currying and Partial Application are related, but they are of different concepts.

Partial application transforms a function into another function with smaller arity.

Currying

Named after Haskell Brooks Curry, currying is the process of breaking down a function into a series of functions that each take a single argument. In other words, Currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.

In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.

That is, when we turn a function call add(1,2,3) into add(1)(2)(3) . By using this technique, the little piece can be configured and reused with ease.

Why it’s useful ?

Currying helps you to avoid passing the same variable again and again.
It helps to create a higher order function. It’s extremely helpful in event handling.
Little pieces can be configured and reused with ease.

Currying example

Here’s a simple example. We’ll write a function sum3 takes three numbers and returns their sum.

In a standard way, the function is implemented like so:

However, if we provide too few parameters, or too many parameters, then it can have unintended consequences.

add(1,2) –> NaN
add(1,2,3,4) –> 6 //Extra parameters will be ignored.

The curried version of sum3 behaves a differently. It accepts one argument and returns one function. The returned function also accepts one argument and also returns another function that also accepts one argument and …

This cycle continues until the returned function accepts the last argument. The last one in the chain, finally returns the sum.

This works because JS supports closures.

Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c). JavaScript implementations usually both keep the function callable normally and return the partial if arguments count is not enough.

Another example of why currying is useful

Of course, currying comes in handy when you want to:

1. Write little code modules that can be reused and configured with ease, much like what we do with npm:

For example, you own a store🏠 and you want to give 10%💵 discount to your fav customers:

When a fav customer buys a good worth of $500, you give him:

You see that in the long run, we would find ourselves calculating discount with 10% on a daily basis.

We can curry the discount function, so we don’t always add the 0.10 discount:

Now, we can now calculate only with price of the goods bought by your fav customers:

Again, it happens that, some fav customers are more important than some fav customers- let’s call them super-fav customers. And we want to give 20% discount to our super-fav customers.

We use our curried discount function:

We setup a new function for our super-fav customers by calling the curry function discount with a 0.2 value , that is 20%.

The returned function twentyPercentDiscount will be used to calculate discounts for our super-fav customers:

2. Avoid frequently calling a function with the same argument:

For example, we have a function to calculate the volume of a cylinder:

To resolve this, you curry the volume function(like we did earlier):

We can define a specific function for a particular cylinder height:

How does Curry work?

Currying works by natural closure.The closure created by the nested functions to retain access to each of the arguments.So inner function have access to all arguments.

Additional Examples

ref – https://www.sitepoint.com/currying-in-functional-javascript/

You can see how powerful this approach is, especially if you need to create a lot of very detailed custom functions.
The only problem is the syntax. As you build these curried functions up, you need to keep nesting returned functions,
and call them with new functions that require multiple sets of parentheses, each containing its own isolated argument.
It can get messy.

To address that problem, one approach is to create a quick and dirty currying function that will take
the name of an existing function that was written without all the nested returns.
A currying function would need to pull out the list of arguments for that function,
and use those to return a curried version of the original function:

Currying is an incredibly useful technique from functional JavaScript.
It allows you to generate a library of small, easily configured functions that behave consistently,
are quick to use, and that can be understood when reading your code. Adding currying to your coding practice
will encourage the use of partially applied functions throughout your code, avoiding a lot of potential repetition,
and may help get you into better habits about naming and dealing with function arguments.

instance of (js)

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

User Object

Create Prototype Object and Connect

Whenever we want a object to derive from other objects, we derive their prototype functionalities.
We do so like this:

1) create the an object X with its property __proto__ pointing to the prototype object via Object.create.
2) have their function constructor’s prototype point to that object X.
3) have the object X’s constructor point back to the constructor function
4) Now that we are done connecting, we can use a callback to execute any prototype implementations.

Admin and SuperAdmin

Create the Admin constructor function, initialize its subclass, and then initiate its own property.
Since we want to derive from the user prototype, we put in Admin as the constructor, User.prototype as the prototype object we want to derive from, and finally, implement the prototype functionalities.

instanceof

The instanceof operator tests whether the prototype property of the [Constructor function] appears anywhere in the prototype chain of the [object].

instanceof is an operator and it expects two operands:

– an object
– Constructor function

it will test if the passed function prototype property exists on the chain of the object.

For example:

Diagram wise:

Hence, as we can see, for object u,

the prototype property of Admin appears in the prototype chain.
the prototype property of User appears in the prototype chain.
However, the prototype property of SuperUser DOES NOT appear

isPrototypeOf

the isPrototypeOf is a function available on the Object.prototype object, it lets you test if an specific object is in the prototype chain of another, since this method is defined on Object.prototype, it is be available for all objects.

for example…

static functions used with prototype functions (js)

ref – https://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a ‘static method’.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

When MyClass.prototype.publicMethod can access ‘privileged’ members, it means you can access privileged properties and functions from constructor function.

When MyClass.prototype.publicMethod can access ‘public’ members, it means you can access public functions from the prototype, like so:

Declared and undeclared variables in functions

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Declared variables are constrained in the execution context in which they are declared.

Undeclared variables are always global

…even in inner functions

Let’s declare an inner function called ‘inner’. We have an undeclared variable ‘name’.
That name will be declared as a global. It will be accessible by all scopes.

Chat Room using Node

ref – https://socket.io/get-started/chat

setup

Assuming you have node, npm, nodemon/gulp installed.

First, make a directory called DesktopApp. Then start the process of creating a node project.


npm init

Enter your information for the package.json file.

Install Express:

npm install –save express@4.15.2

Server can push messages to clients. Whenever you write a chat message, the idea is that the server will get it and push it to all other connected clients.

Number of Lines

github source

What does it do

Calculate how many lines are there when you put a long string into a div/span that has a width.

Getting Started

First, let’s set it up. We create a div with id para. We limit it to 68px so we can see the effects of the word break.

html

js

Getting the width of a string involves first putting test text into your div #para. Then,

1) We need to the get element object of #para first. It will contain all the information you need about this element object. We will be using it in the next step to get font and font size info.

2) By using the global window object, we use getComputedStyle of an element object to get style information such as font-size, font-family, background-color…etc.
We do this by calling getPropertyValue on the style object that’s returned. We specify which style attribute we want to get by inserting the style name.

3) then the font size

4) Using JQuery, create a span in your DOM.
Using jQuery, insert your text, apply the font and font size, and call width on it.
It will give you the pixel width on it.

The $.fn is an alias for jQuery.prototype which allows you to extend jQuery with your own functions.
We create our own function textWidth. It takes a paragraph, font, and a fontSize. Then it returns you
the width in pixels.

We first check to see if there’s a property placeholderEl. If it doesn’t exist, we attach the property
to our function. We then create a span element object and append it to the document’s body. We attach the
property placeholderEl to that span object.

We then insert the text into the span, and apply the font and font size to the text using css function.
then we call width on the span object to get the pixel.

thus, so far, you should have something like this in your JS file:

Logic

Now that we can get an accurate width of a paragraph with applied font, let’s take a look at how we’re going to tackle the issue.
note: limit means the end of the width.

A) no-space long word past limit

In the first basic situation, the long word will stay as is. This is because the browser do not break a word. It will only break a sentence, when it detects a space, but will never break a word in half.

B) long word past limit, then space

The second situation is that our long word goes past the limit. Then it has a space. In this case, we have two parts.
– The string left of the space.
– The string right of the space.

The right part of the space then gets broken and starts at the next line. The space is the last character of the first line.

C) long word past limit, with a previous space

When we reach the limit, but there was a previous space. Thus, we have two parts again.
– The string left of the space.
– The string right of the space.

The string to the right of the space gets broken and start at line two. The string left of the space, remains at line 1.

D) long word past limit, with previous multiple spaces

Sometimes, there will be multiple spaces previously. So when we hit the limit, how do we break it? The answer is that we find the last space. We don’t care any previous spaces. All we care about is the last space because we need to see how to break the substring that just went past the limit.

Implementation

We’ll do this in es5.

We first create a function to be new-ed later. It will contain the object’s property and data. We need the basic things such as:
– text (string)
– the width function we’re going to use to calculate string widths on the browser (function)
– font (string)
– fontSize (string)

We also pass in the div element’s id so that we can get the width.

Then, let’s implement a function in the prototype so that all instances will use it.

We can easily get the width of the text by using our textWidth function. However, when you use space ‘ ‘, you’ll get 0. So we do a workaround by giving the strings ‘a’. Then a space a, (‘a a’). That way, we know the width of a. And then, can calculate the width of space.

We calculate the width of the string. If the string is a space, then we simply give it the width of space, which we pass in.
However, if not a space, then we calculate it by passing our text, our font, and font size. We then pass the result into a callback to be processed by others.

The Logic

Given a long text, we run through each character.

1) get width of the char
2) append the width onto a total width.

For every add of a width, we check to see if our total text has passed the limit.

Thus,

using our prototype function getCharWidth. Also, notice “holder”. Holder basically holds the added character so far.
Another thing to notice is that there is a bool to check to see if a previous space exist.

The key is to check for situations when we hit past the limit.
If after passing the limit, and we detect a space, then we gotta save the left side of the string.

In order to do this, we use a ‘holder’ string to hold everything. Also, notice we have calculated the width of the space also.

– passed the limit
– no previous space was detected
– current char is a space

Thus, we save the everything that was held up to now. But where do we save it to?

We simply save it into an array that will represent the formatting of our paragraph.
First sentence is array[0], second array[1]…etc.

Thus, in our constructor function:

now..back to our calcNumOfLines.

where

Basically, if we pass the limit, but no space is found, we just save it. This will satisfy A).
As each additional character is processed, and we find that the current processed character is a space (assuming no previous space), then we simply store it.
This resolves B).

else if we’re past the limit and the character is NOT a space, and there was a previous space, then we resolve cases
C) and D)

full source
https://github.com/redmacdev1988/NumberOfLines

Mustache templating for displaying data (JS)

ref –
https://github.com/janl/mustache.js/
https://medium.com/@koalamango/javascript-templating-with-mustache-js-b50919cb4f57
https://www.elated.com/articles/easy-html-templates-with-mustache/

Templates are a great way to separate your website’s code from its design.

Mustache is a logic-less template syntax. It can be used for HTML, config files, source code – anything.

It works by expanding tags in a template using values provided in a hash or object

One of Mustache’s big plus points is that is logic-less, which means it keeps your templates very neat and tidy. There are no messy if … then or looping constructs embedded within a Mustache template; it’s all just markup and simple Mustache tags. All the logic is hidden away inside your data objects (and the code that creates or fetches them).

A mustache template is a string that contains any number of mustache tags.

Tags are indicated by the double mustaches that surround them.
{{person}} is a tag, as is {{#person}}

Using mustache basics

  • First, we’ll include mustache js file
  • Second, we’ll create a template with tags
  • Then, we’ll use a object’s values provided by its properties
  • Finally, we’ll see the output from the template + object by using Mustache.render

include the mustache js file in your header

Create the template

The template is a string.
For example: “{{name}} is a {{occupation}}

The tags are:
{{name}}
{{occupation}}

It expands the tags by using object view.
It looks inside this object for properties name and occupation. Then it would expand the tags with the values occupied at properties name, and occupation.

Load the template

Then, simply execute our tags, templates, objects, and render them.
Id person for paragraph p is to hold the result.

Another Example

This time, we introduce the concept of sections.

Sections render blocks of text one or more times, depending on the value of the key in the current context. A section begins with a hashtag and ends with a slash:

template:

The behavior of the section is determined by the value of the key:

object:

Since the object property is true, we display what’s between Robot tags.

My name is Pinocchio!

Your output when you run the web file is:

Hello Pinocchio You live in the woods! Well, you are friends with animals

Inverted Sections

An inverted section begins with a caret (hat) and ends with a slash.

Inverted section means when its false, it displays. When true, it won’t display.

template:

object:

Since Robot is false, let’s display what’s in between the Robot tags because this is an inverted section.

No content!

Another Example

In this next example, we’ll first use textarea to hold strings that can represent our templates and data objects. You can specify the strings in your html code, or simply have the user enter them via the web page.

In html, you can put the contents of the textarea in between textarea tags. Thus, that is the text that will be appear when the textarea tags are rendered on the web page. In our case, we put the template string inside the textarea with id template.

When we’re processing the code, we need to get whatever the input is from the textarea “template”. Thus, we get the string from the textarea via javascript like so:

In, Mustache.Render(template, object), the template parameter needed is a string. Thus, our templateStr can simply be passed in.

The string we pass into the textarea “data” is the object. However, the object must be a code evaluation. In other words, we have to convert the string into code. We can use javascript’s eval function.

Remember that whatever variable you decide to use for the object in dataStr must be used in code.

In our case, it is “hadoken”.

In our js, we basically get the data from the textareas. Then pass them into Mustache.render function. It returns the result that we need.

And we finally throw that result into the html.

js

Source Code

html

css

js

new (js)

ref – https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Prototype and Inheritance in JS (non-class)

Creating a user-defined object requires two steps:

1) Define the object type by writing a function.

2) Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name and properties. An object can have a property that is itself or another object.

When the code new Foo(…) is executed, the following things happen:

1) A new object is created, inheriting from Foo.prototype.

2) The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.

3) Normally constructors don’t return a value.

If the constructor function doesn’t explicitly return an object, the object created in step 1 is used instead.
However, sometimes, they can choose to do so if they want to override the normal object creation process of using step 1.
If they do return an object in the constructor function, then the object returned by the constructor function becomes the result of the whole new expression. Reference p would then point to this returned object.

Built in Methods (js)

ref – https://medium.com/@_bengarrison/javascript-es6-exploring-the-new-built-in-methods-b62583b0a8e6
https://stackoverflow.com/questions/33164725/confusion-between-isnan-and-number-isnan-in-javascript
https://ponyfoo.com/articles/es6-number-improvements-in-depth

Use Object.assign to assign properties of objects over to your destination object.

Using Object.assign, if there already exist a property/value, and you assign a new property that has the same name over, then the existing property/value gets replaced.

Using Object.assign, we can also do a deep copy of an object.

find and findIndex both find elements for you. It is important to note that find() will return the FIRST element in the Array that satisfies the provided testing function.

Use find to see if ‘d’ exists.


find – looping: a
find – looping: b
find – looping: c
find – looping: c
find – looping: d
res: d

Use findIndex to see if ‘c’ exists.


findIndex – looping: a
findIndex – looping: b
findIndex – looping: c
2

Number.isNaN

The reason isNaN() is “broken” is because, ostensibly, type conversions aren’t supposed to happen when testing values.

That is the issue Number.isNaN() is designed to address.

In particular, Number.isNaN() will only attempt to compare a value to NaN if the value is a number-type value.

Any other type will return false, even if they are literally “not a number”, because the type of the value NaN is number.

You can also think of it as anything that’s not NaN when passed to Number.isNaN will return false, while passing NaN into it will yield true.

The ES5 global.isNaN method, in contrast, casts non-numeric values passed to it before evaluating them against NaN, using Number(…)

That produces significantly different results. The example below produces inconsistent results because, unlike Number.isNaN, isNaN casts the value passed to it through Number first.

Number.isNaN will return false immediately if the argument is not a Number

while isNaN first converts the value to a Number

For isNaN():

then it does a NaN === NaN comparison, which results to true.

for Number.isNumber() , as mentioned earlier, we check to see the type of the argument is a Number. If its not a Number, it returns false immediately!

Infinity is actually NOT infinity, it a numeric value that represents Infinity. The actual value is 1.797693134862315E+308. The same for -Infinity, -1.797693134862315E+308

static and non-static (js)

ref – https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1

Static methods, like many other features introduced in ES6, are meant to provide class-specific methods for object-oriented programming in Javascript.

Static methods are often used to create utility functions for an application.

Static methods are called without instantiating their class…

thus, when we call static “triple”, you will won’t see the log in the constructor executed.

Static methods…are also not callable when the class is instantiated.

Since these methods operate on the class instead of instances of the class, they are called on the class.

Say we have a subclass to a parent class, any static methods that we declared are available to the subclasses as well