Skip to content

Instantly share code, notes, and snippets.

@fwg
Forked from line-o/PS.js
Created January 27, 2012 13:25
Show Gist options
  • Save fwg/1688755 to your computer and use it in GitHub Desktop.
Save fwg/1688755 to your computer and use it in GitHub Desktop.
node js module to find a representation for a string with chemical elements
.idea/
*~
*.swp
{
"name": "PSErep",
"description": "A module for converting a word into a sequence of chemical element names",
"version": "0.1.0"
}
var elements = "H,He,Li,Be,B,C,N,O,F,Ne,L,Na,Mg,Al,Si,P,S,Cl,Ar,M,K,Ca,Sc,Ti,V."
+ "Cr,Mn,Fe,Co,Ni,Cu,Zn,Ga,Ge,As,Se,Br,Kr,Rb,Sr,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,"
+ "Cd,In,Sn,Sb,Te,I,Xe,Cs,Ba,Hf,Ta,W,Re,Os,Ir,Pt,Au,Hg,Tl,Pb,Bi,Po,At,Rn,Fr,"
+ "Ra,Rf,Db,Sg,Bh,Hs,Mt,Ds,Rg,Cn,Uut,Uuq,Uup,Uuh,Uus,Uuo,Q,La,Ce,Pr,Nd,Pm,"
+ "Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu,Ac,Th,Pa,U,Np,Pu,Am,Cm,Bk,Cf,Es,Fm,Md,No,Lr"
.split(',');
function matcher(a) {
var s = a.toLowerCase()
return function(b) {
return !s.indexOf(b.toLowerCase())}}
function flatten(a){
if(!(a instanceof Array)) return [a]
function rc(ar,el){
return ar.concat(flatten(el)) }
return a.reduce(rc, [])}
function build (str, finds) {
if(str=="" || str==null) return finds
var z = elements.filter(matcher(str)).map(function(match) {
return flatten(build(str.slice(match.length), finds.concat([match])))})
return z.length? z : finds }
// get PSE representations of a string
// @return an array of representations
exports.getRep = function(str) {
return build(str, [])}
var c = require('./chemelemrep');
console.log( c.getRep('p') );
console.log( c.getRep('pb') );
console.log( c.getRep('pbr') );
console.log( c.getRep('asd') );
console.log( c.getRep('punk') );
@line-o
Copy link

line-o commented Feb 7, 2012

There seems to be a typo at the end of line 1 of PSErep.js : [...]V_._"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment