Categories
discuss

Ways to create a Set in JavaScript?

In Eloquent JavaScript, Chapter 4, a set of values is created by creating an object and storing the values as property names, assigning arbitrary values (e.g. true) as property values. To check if the value is already contained in the set, the in operator is used:

var set = {};

if (!'Tom' in set) { 
  set.Tom = true;
}

Is this idiomatic JavaScript? Wouldn’t be using an array even better?

var set = [];

if (!'Tom' in set) { 
  set.push = 'Tom';
}

Answer

Sets are now available in ES2015 (aka ES6, i.e. ECMAScript 6). ES6 has been the current standard for JavaScript since June 2015.

ECMAScript 6 has the data structure Set which works for arbitrary values, is fast and handles NaN correctly. –Axel Rauschmayer, Exploring ES6

First two examples from Axel Rauschmayer’s book Exploring ES6:

Managing single elements:

> let set = new Set();
> set.add('red')

> set.has('red')
true
> set.delete('red')
true
> set.has('red')
false

Determining the size of a Set and clearing it:

> let set = new Set();
> set.add('red')
> set.add('green')

> set.size
2
> set.clear();
> set.size
0

I would check out Exploring ES6 if you want to learn more about Sets in JavaScript. The book is free to read online, but if you would like to support the author Dr. Axel Rauschmayer you can purchase the book for around $30.

If you want to use Sets and ES6 now you can use Babel, the ES6 to ES5 transpiler, and its polyfills.

Edit: As of June 6th, 2017 most of the major browsers have full Set support in their latest versions (except IE 11). This means you may not need babel if you don’t care to support older browsers. If you want to see compatibility in different browsers including your current browser check Kangax’s ES6 compatibility table.

EDIT:

Just clarification on initialization. Sets can take any synchronous iterable in their constructor. This means they can take not just arrays but also strings, and iterators. Take for example the following array and string initialization of a set:

const set1 = new Set(['a','a','b','b','c','c']);
console.log(...set1);
console.log(set1.size);
const set2 = new Set("aabbcc");
console.log(...set2);
console.log(set2.size);

Both outputs of the array and string are the same. Note that ...set1 is the spread syntax. It appears that each element of the iterable is added one by one to the set, so since both the array and string have the same elements and since the elements are in the same order the set is created the same. Another thing to note about sets is when iterating over them the iteration order follows the order that the elements were inserted into the set. Here’s an example of iterating over a set:

const set1 = new Set(['a','a','b','b','c','c']);
for(const element of set1) {
  console.log(element);
}

Since you can use any iterable to initialize a set you could even use a iterator from a generator function. Here is two such examples of iterator initializations that produce the same output:

// a simple generator example
function* getLetters1 () {
  yield 'a';
  yield 'a';
  yield 'b';
  yield 'b';
  yield 'c';
  yield 'c';
}

// a somewhat more commonplace generator example
// with the same output as getLetters1.
function* getLetters2 (letters, repeatTimes) {
  for(const letter of letters) {
    for(let i = 0; i < repeatTimes; ++i) { 
      yield letter;
    }
  }
}

console.log("------ getLetters1 ------");
console.log(...getLetters1());
const set3 = new Set(getLetters1());
console.log(...set3);
console.log(set3.size);

console.log("------ getLetters2 ------");
console.log(...getLetters2('abc', 2));
const set4 = new Set(getLetters2('abc', 2));
console.log(...set4);
console.log(set4.size);

These examples’ generator functions could just be written to not repeat, but if the generator function is more complicated and as long as the following doesn’t impact performance too negatively you could use the Set method to help get only values from a generator that don’t repeat.

If you want to know more about sets without reading Dr. Rauschmayer’s chapter of his book you can check out the MDN docs on Set. MDN also has more examples of iterating over a set such as using forEach and using the .keys, .values, and .entries methods. MDN also has examples such as set union, set intersection, set difference, symmetric set difference, and set superset checking. Hopefully most of those operations will become available in JavaScript without needing to build your own functions supporting them. In fact, there is this TC39 proposal for new Set methods which should hopefully add the following methods to Set in JavaScript at some future point in time if the proposal reaches stage 4:

  • Set.prototype.intersection(iterable) – method creates new Set instance by set intersection operation.
  • Set.prototype.union(iterable) – method creates new Set instance by set union operation.
  • Set.prototype.difference(iterable) – method creates new Set without elements present in iterable.
  • Set.prototype.symmetricDifference(iterable) – returns Set of elements found only in either this or in iterable.
  • Set.prototype.isSubsetOf(iterable)
  • Set.prototype.isDisjointFrom(iterable)
  • Set.prototype.isSupersetOf(iterable)
Categories
discuss

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec

How do I achieve that with Javascript?

Answer

You can build it manually:

var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();

and to force two digits on the values that require it, you can use something like this:

("0000" + 5).slice(-2)

Which would look like this:

var m = new Date();
var dateString =
    m.getUTCFullYear() + "/" +
    ("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
    ("0" + m.getUTCDate()).slice(-2) + " " +
    ("0" + m.getUTCHours()).slice(-2) + ":" +
    ("0" + m.getUTCMinutes()).slice(-2) + ":" +
    ("0" + m.getUTCSeconds()).slice(-2);

console.log(dateString);
Categories
discuss

How did Evernote implement their rich text editor on Android?

As asked here: How did Evernote implement their rich text editor on iOS?

I’ve been struggling to find a third-party library for rich text editing on Android. I’ve just installed Evernote’s Android client and they have a pretty nice solution. Anyone in the know as to how they did it?

edit

For anyone looking, the WordPress app contains a WYSIWYG-ish editor that’s open-source:

https://android.trac.wordpress.org/browser/trunk/src/org/wordpress/android/EditContent.java

Answer

here are some links that should help you get started:

http://code.google.com/p/android-richtexteditor/

Rich Text Box in android

Categories
discuss

how to convert a string to float and avoid using try/catch in java?

There are some situation that I need to convert string to float or some other numerical data-type but there is a probability of getting some nonconvertible values such as “-” or “/” and I can’t verify all the values beforehand to remove them. and I want to avoid using try/catch for this matter , is there any other way of doing a proper conversion in java? something similar to C# TryParse?

Answer

The simplest thing I can think of is java.util.Scanner . However this approach requires a new Scanner instance for each String.

String data = ...;
Scanner n = new Scanner(data);
if(n.hasNextInt()){//check if the next chars are integer
  int i = n.nextInt();   
}else{

}

Next you could write a regex pattern that you use to check the String (complex to fail too big values) and then call Integer.parseInt() after checking the string against it.

Pattern p = Pattern.compile("insert regex to test string here");
String data = ...;
Matcher m = p.matcher(data);
//warning depending on regex used this may 
//only check part of the string
if(m.matches()){
  int i = Integer.parseInt(data);
}

However both of these parse the string twice, once to test the string and a second time to get the value. Depending on how often you get invalid strings catching an exception may be faster.

Categories
discuss

How can I convert a PNG file to PDF using java?

Are there any open source libraries that I can use?

Answer

itext may help you. you don’t really convert a png to pdf but create a pdf with a png in it. simple example:

Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("C:/test.pdf"));
document.open();
Image image = Image.getInstance(getClass().getResource("/logo.png"));
document.add(image);
document.close();
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..